Converting a string to int (or something else), is there a preferred way?

Sometimes I wonder when converting strings to other types, like int32, is one way better than another, or is it just a matter of taste?

Convert.ToInt32("123")

or

Int32.Parse("123")

or

Any other way?

Not considering the case if it is not a valid int in this question.

+3
source share
4 answers

Convert.ToInt32 is implemented as follows ...

int.Parse(value, CultureInfo.CurrentCulture);

... which matches your declared alternative, except that it takes into account the culture settings. The int.Parse method is implemented as follows ...

Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));

... Number - , . Number.ParseInt32 ...

[MethodImpl(MethodImplOptions.InternalCall)]

... , CLR.

+4

Conver.ToInt32 Int32.Parse , null. Convert.ToInt32 :

public static int ToInt32(string value)
{
    if (value == null)    
        return 0;

    return Int32.Parse(value, CultureInfo.CurrentCulture);
}

. , "0" 0. Visual Basic:

, Visual Basic 6 Visual Basic.NET, Visual Basic 6. , # , Visual Basic .

, -VB-, Int32.Parse Int32.TryParse.

+2

When converting from string to int, I always use int.TryParse. Because you are not always sure that you can convert a string to int. Like this:

string temp="222";
int intValue;
if(int.TryParse(temp,out intValue))
{
    //Something
}
+1
source

As V4Vendetta has shown, it is better to use TryParse to avoid conversion related exceptions.

int result = 0;

a = "3";
string b = "b";
string c = "2147483648"; //int32 max value + 1

int.TryParse(a, out result); // returns true result=3
int.TryParse(b, out result); // returns false result=0
int.TryParse(c, out result); // returns false result=0
0
source

All Articles