When to use a Cast or Convert

C#Casting

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

See Diff Between Cast and Convert on another forum

Answer

> 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 returns 0, whereas Int32.Parse throws an ArgumentNullException.
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()).


UPDATE

Link on top is broken, see this answer on StackOverflow.

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution 8 - C#

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

Solution 9 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGageView Question on Stackoverflow
Solution 1 - C#GregView Answer on Stackoverflow
Solution 2 - C#DavidView Answer on Stackoverflow
Solution 3 - C#SebView Answer on Stackoverflow
Solution 4 - C#STOView Answer on Stackoverflow
Solution 5 - C#fire.eagleView Answer on Stackoverflow
Solution 6 - C#Gerard ONeillView Answer on Stackoverflow
Solution 7 - C#Yuriy FaktorovichView Answer on Stackoverflow
Solution 8 - C#MashiMaroView Answer on Stackoverflow
Solution 9 - C#Tyler HeersView Answer on Stackoverflow