c# - Why use Convert.ToInt32 over casting? -
this question has answer here:
- when use cast or convert 9 answers
a question cropped @ work today how convert object specific type (an int
), said cast it:
int = (int)object;
a colleague said use convert.toint32()
.
int = convert.toint32(object)
what's difference between convert.toint32()
, direct object cast?
not every object can cast directly int
. example, following not compile:
string s = "1"; int = (int)s;
because string
not implicitly convertible int
.
however, legal:
string s = "1"; int = convert.toint32(s);
as side note, both casting , convert
can throw exceptions if input object cannot converted. however, int.tryparse
not throw if fails; rather, returns false (but takes in string, have .tostring()
input object before using it):
object s = "1"; int i; if(int.tryparse(s.tostring(), out i)) { // has value of 1 }
Comments
Post a Comment