简体   繁体   中英

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

Sometimes i wonder, when converting strings to other types, for example int32, is one way better than the other, or is it just a matter of taste?

Convert.ToInt32("123")

or

Int32.Parse("123")

or

Some other way?

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

The Convert.ToInt32 is actually implemented the following way...

int.Parse(value, CultureInfo.CurrentCulture);

...which is the same as your stated alternative except it takes into account the culture settings. The int.Parse method is itself implemented the following way...

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

...where Number is an internal class that you cannot call directly. The Number.ParseInt32 method is marked with the following attribute...

[MethodImpl(MethodImplOptions.InternalCall)]

...showing that it is implemented inside the CLR itself.

Main difference between Conver.ToInt32 and Int32.Parse is how the treat null strings. Convert.ToInt32 returns default value in this case:

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

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

I don't like that. I think only "0" should be parsed to 0 . This behavior initially was designed for Visual Basic programmers :

This is a set of conversion methods for programmers migrating from Visual Basic 6 to Visual Basic .NET that mirrored the behavior of the existing Visual Basic 6 conversion methods. The assumption was that C# programmers would be more comfortable with casting operators, whereas Visual Basic had traditionally used conversion methods for type conversion.

So, as non-VB programmer, I'd go with Int32.Parse and Int32.TryParse .

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

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

As V4Vendetta suggested it is better to use TryParse to avoid exceptions related to converting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM