84

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.

1
  • 5
    I disagree with my question being an exact duplicate of this question. This question asks when to use a cast or convert and the accepted answer below states, "It is really a matter of choice whichever you use." My question specifically asks for the differences between casting and using Convert.To(). Therefore, my question serves as a supplement to your question.
    – user5398447
    Mar 14, 2013 at 16:13

9 Answers 9

80

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.

1
  • 1
    How does this affect when using Enums? Jun 9, 2016 at 19:01
41

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.

6
  • 73
    IMPORTANT : Another difference I noted recently was that "Cast" casts 1.63 to 1, where as "Convert" converts 1.63 to 2. So basically convert rounds as well as converts but cast truncates values after the decimal point. Sep 3, 2012 at 5:11
  • Sometimes TryParse is not available. Mar 26, 2014 at 17:51
  • 3
    The Compact Framework lacks TryParse: stackoverflow.com/questions/22670260/… Mar 26, 2014 at 18:58
  • 2
    Just for the reference for @AbijeetPatro 's comment, quoted from C# 5.0 in a Nutshell by Joseph Albahari and Ben Albahari. Copyright 2012 Joseph Albahari and Ben Albahari, 978-1-449-32010-2. When you cast from a floating-point number to an integral, any fractional portion is truncated; no rounding is performed. The static class System.Convert provides methods that round while converting between various numeric types Nov 23, 2015 at 10:22
  • 1
    Where has OP said that he wants to convert strings? If a cast is an option it can't be a string. Aug 29, 2018 at 14:28
13

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.

6

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.

4

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.

2

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.

1

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.

0

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

1
  • 1
    This is not because of cast, this is conversion rules. When you divide 2 floats, you receive double value 64.999999068677411, when casting to int it truncates to only integer part. But this will return 65: (int)(float)(a / b)), because in float it's exactly 65, not 64.99(9). Same for decimal. On the contrast Convert rounds up the result, thus it returns 65 here, but 64.49 would be 64. Funny thing is Intellisense says cast to float is redundant, while without it returns 64
    – Vitaly
    Jul 26, 2018 at 14:27
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.