views:

121

answers:

5

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 gain with using one?

Also which situations should each be used for. Currently I'm more inclined to use Convert but I don't have a reason to go either way. In my mind I see them both accomplishing the same goal.

+5  A: 

See this post on another forum: http://en.allexperts.com/q/C-3307/Diff-Cast-Convert.htm

Personally, I use neither, and tend to use the TryParse functions, as in System.Int32.TryParse()

David Stratton
A: 

A cast just tells the compiler that this object is actually an implementation of a different type and to treat it like the new implementation now. Whereas a convert says that this doesn't inherit from what you're trying to convert to, but there is a set way to so it. For example, say we're turning "16" into an int. "16" is a string, and does not inherit from int in any way. But, it is obvious that "16" could be turned into the int 16.

fire.eagle
+2  A: 

Not all types supports conversion like

int i = 0;
decimal d = (decimal)i;

because it is needed to implement explicit operator (http://msdn.microsoft.com/en-us/library/xhbhezf4(VS.71).aspx). But .NET also provide IConvertible interface ( http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx ), so any type implements that interface may be converted to most framework built-in types. And finally, Convert class helps to operate with types implements IConvertible interface.

STO
A: 

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.

Yuriy Faktorovich
+6  A: 

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.

Greg