Alex Rivera | Logout

When to use a Cast or Convert

Asked 2010-07-02T19:48:32.610
87

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.

Edit
Report

3 Answers

43

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.

answered 2010-07-02T19:53:38.367
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.

answered 2010-07-02T19:55:02.933
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.

answered 2010-07-02T19:54:07.053

Your Answer