c# - Why use Convert.ToInt32 over casting? -


this question has answer here:

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

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -