83

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.

Jonas
  • 4,107
  • 3
  • 21
  • 25
Gage
  • 7,365
  • 9
  • 47
  • 77
  • 5
    I [disagree](http://stackoverflow.com/questions/15394032/difference-between-casting-and-using-the-convert-to-method#comment21762601_15394032) with [my question](http://stackoverflow.com/q/15394032/1121302) 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. –  Mar 14 '13 at 16:13

9 Answers9

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.

Greg
  • 16,540
  • 9
  • 51
  • 97
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.

Sergio
  • 2,078
  • 3
  • 24
  • 41
David
  • 72,686
  • 18
  • 132
  • 173
  • 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. – Abijeet Patro Sep 03 '12 at 05:11
  • Sometimes TryParse is not available. – Shaun Luttin Mar 26 '14 at 17:51
  • 3
    The Compact Framework lacks TryParse: http://stackoverflow.com/questions/22670260/does-the-net-compact-framework-have-the-tryparse-methods-where-is-the-document – Shaun Luttin Mar 26 '14 at 18:58
  • Casting can only turn boxed values (stored in "object-typed" variables) to the type of the pointed value while Convert will both unbox the variable and convert to the any type. `object o = 1L; double d = (double)o;` will fail while `Convert.ToDouble(o)` works. – Domino Apr 27 '15 at 18:33
  • 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` – Burak Karakuş Nov 23 '15 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. – Tim Schmelter Aug 29 '18 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.

Seb
  • 839
  • 8
  • 13
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.

bjan
  • 2,000
  • 7
  • 32
  • 64
STO
  • 10,390
  • 8
  • 32
  • 32
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.

fire.eagle
  • 2,723
  • 1
  • 21
  • 23
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.

Gerard ONeill
  • 3,914
  • 39
  • 25
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.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
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

MashiMaro
  • 39
  • 7
  • 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 '18 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

Tyler Heers
  • 134
  • 4