The following code throws an compile-time error like
Cannot convert type 'string' to 'int'
string name = Session["name1"].ToString(); int i = (int)name;
whereas the code below compiles and executes successfully:
string name = Session["name1"].ToString(); int i = Convert.ToInt32(name);
I would like to know:
Why does the the first code generate a compile-time error?
What's the difference between the 2 code snippets?
Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.
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.
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.
Thus int32 would be limited to a value between (-256^4/2) and (256^4/2-1). And int64 would be limited to a value between (-256^8/2) and (256^8/2-1).
(int)foo
is simply a cast to the Int32
(int
in C#) type. This is built into the CLR and requires that foo
be a numeric variable (e.g. float
, long
, etc.) In this sense, it is very similar to a cast in C.
Convert.ToInt32
is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int
(most notably, parsing a string
). You can see the full list of overloads for this method here on MSDN.
And as Stefan Steiger mentions in a comment:
Also, note that on a numerical level,
(int) foo
truncatesfoo
(ifoo = Math.Floor(foo)
), whileConvert.ToInt32(foo)
uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaningifoo = Math.Round(foo)
). The result is thus not just implementation-wise, but also numerically not the same.
(this line relates to a question that was merged) You should never use (int)someString
- that will never work (and the compiler won't let you).
However, int int.Parse(string)
and bool int.TryParse(string, out int)
(and their various overloads) are fair game.
Personally, I mainly only use Convert
when I'm dealing with reflection, so for me the choice is Parse
and TryParse
. The first is when I expect the value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to check if it is a valid integer - I can then decide what to do when it is/isn't.
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