I am curious to know what the difference is between a cast to say an int
compared to using Convert.ToInt32()
. Is there some sort of performance gai
string number = "123abc";
int num;
Int32.TryParse(number, out num); // no exception thrown at this call
Convert.ToInt32(number); // exception IS thrown at this call
Cast when it's really a type of int
, Convert when it's not an int
but you want it to become one.
For example int i = (int)o;
when you know o is an int
int i = Convert.ToInt32("123")
because "123" is not an int, it's a string representation of an int.
There are a lot of overloads for Convert.ToInt32
that can take for example a string. While trying to cast a string to an int will throw a compile error. The point being is they're for different uses. Convert is especially useful when you're not sure what type the object you're casting from is.
There is one more reason you should use Convert.ToInt32 instead of a cast.
For example:
float a = 1.3f;
float b = 0.02f;
int c = (int)(a / b);
int d = Convert.ToInt32(a / b);`
The result is c = 64 and d = 65
See Diff Between Cast and Convert on another forum
The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse (read remarks).
So the only difference is that if a null string is passed it returns0
, whereasInt32.Parse
throws anArgumentNullException
.
It is really a matter of choice whichever you use.
Personally, I use neither, and tend to use the TryParse
functions (e.g. System.Int32.TryParse()).
Link on top is broken, see this answer on StackOverflow.
There is another difference. "Convert" is always overflow-checked, while "cast" maybe, depending on your Settings and the "checked" or "unchecked" keyword used.
To be more explicit. Consider the code:
int source = 260;
byte destination = (byte)source;
Then destination will be 4 without a warning.
But:
int source = 260;
byte destination = Convert.ToByte(source);
will give you a exception.