Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Convert.ToInt32 over casting? [duplicate]

Tags:

c#

.net

casting

A question cropped up at work today about how to convert an object into its specific type (an int), I said to cast it:

int i = (int)object;

a colleague said to use Convert.ToInt32().

int i = Convert.ToInt32(object)

What's the difference between Convert.ToInt32() and a direct object cast?

like image 422
m.edmondson Avatar asked Feb 09 '11 16:02

m.edmondson


People also ask

Why do we use convert ToInt32?

ToInt32(String, IFormatProvider) Method. This method is used to converts the specified string representation of a number to an equivalent 32-bit signed integer, using the specified culture-specific formatting information.

What does convert ToInt32 mean?

ToInt32(String, Int32) Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer. ToInt32(UInt64) Converts the value of the specified 64-bit unsigned integer to an equivalent 32-bit signed integer.

What is the difference between convert ToInt32 and int parse?

Convert. ToInt32 allows null value, it doesn't throw any errors Int. parse does not allow null value, and it throws an ArgumentNullException error.

What is the difference between int TryParse () & Convert ToInt32 () in C#?

Int32 type. The Convert. ToInt32 method uses Parse internally. The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter.


1 Answers

Not every object can be cast directly to int. For example, the following will not compile:

string s = "1";
int i = (int)s;

because string is not implicitly convertible to int.

However, this is legal:

string s = "1";
int i = Convert.ToInt32(s);

As a side note, both casting and Convert can throw exceptions if the input object cannot be converted. However, int.TryParse does not throw if it fails; rather, it returns false (but it only takes in a string, so you have to .ToString() your input object before using it):

object s = "1";
int i;
if(int.TryParse(s.ToString(), out i))
{
   // i now has a value of 1
}
like image 96
Mark Avenius Avatar answered Nov 15 '22 14:11

Mark Avenius