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
Throwing in my 2c -- it seems that a conceptual distinction might be useful. Not that I'm an expert.. :
Casting is changing the representative type. So "32" and 32L and 32.0f seem reasonable to cast between each other. c# will not support the "32" automatically, but most dynamic languages will. So I'll use the (long)"32" or (String)32L. When I can. I also have another rule -- Casting should be round trippable.
Converting doesn't have to be round trippable, and can simply create a totally new object.
The Grey area is for example the string "32xx". A case can be made that when you cast it, it becomes 32L (the number was parsed until it couldn't be). Perl used this. But then this violates my round trip requirement. The same goes for 32.5f to 32L. Almost all languages including very statically typed ones allow this, and it too fails the round trippable rule. It is grey in that if you allow "32" to be cast, then at compile time you don't know if it might be "32xxx".
Another distinction that can be made is to just use casting for "IsA" and not for "makeLookLikeA". So if you know a string comes from a database but is actually an int in the unofficial schema, feel free to use a cast (although in this case c# wants you to use Convert anyway). The same would go for a float. But not for when you are just using the cast to truncate the float. This distinction also accounts for DownCasting and UpCasting -- the object was always 'IsA', but the type might have been generalized for a list.
Not all types supports conversion like
int i = 0;
decimal d = (decimal)i;
because it is needed to implement explicit operator. But .NET also provide IConvertible interface, 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.
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.