A question cropped up at work today about how to convert an object into its specific type (an int
), I said to cast it:
int i = (int)object;
a colleague said to use Convert.ToInt32()
.
int i = Convert.ToInt32(object)
What's the difference between Convert.ToInt32()
and a direct object cast?
ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.
ToInt32(String, Int32) Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer. ToInt32(UInt64) Converts the value of the specified 64-bit unsigned integer to an equivalent 32-bit signed integer.
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
Int32 type. The Convert. ToInt32 method uses Parse internally. The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter.
Not every object can be cast directly to int
. For example, the following will not compile:
string s = "1";
int i = (int)s;
because string
is not implicitly convertible to int
.
However, this is legal:
string s = "1";
int i = Convert.ToInt32(s);
As a side note, both casting and Convert
can throw exceptions if the input object cannot be converted. However, int.TryParse
does not throw if it fails; rather, it returns false (but it only takes in a string, so you have to .ToString()
your input object before using it):
object s = "1";
int i;
if(int.TryParse(s.ToString(), out i))
{
// i now has a value of 1
}
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