I could write the following to convert an object to an integer.
Convert.ToInt32(myObject);
But I could also write
Int.Parse(myObject.ToString());
Thanks in advance.
- Is there any difference?
Yes, Int32.parse(myObject.ToString());
takes a detour to string, that will usually work but it is unnecessary and it might fail or give a different result.
- Which one should I be using?
In general, Convert.ToInt32(myObject);
But it depends on what type of data you want to convert.
If myObject = '1';
, do you want 1
or 49
?
If myObject = false;
, do you want 0
or an exception ?
etc
This how Convert.ToInt32
method source looks like
public static int ToInt32(object value) {
return value == null? 0: ((IConvertible)value).ToInt32(null);
}
As long as your object implement IConvertible
interface you should call this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With