简体   繁体   中英

How to check if string is number and assign it to nullable int?

I have nullable int[] and string.

string someStr = "123"; 

int? siteNumber = null;
string siteName= null;

At some point I need to check if a string is number.

For this purpose I tryed this:

if (int.TryParse(someStr, out siteNumber)) 
    { } 
else 
    siteName = siteDescription;

But because siteNumber is nullable I get this error:

cannot convert from 'out int?' to 'out int' 

How can I check if string is number and if it is I need to assign it to nullable int?

You could use an intermediate variable because the out parameters types should match fully.

int siteNumberTemp;
if (int.TryParse(someStr, out siteNumberTemp)) 
{
   siteNumber = siteNumberTemp;
} 
else 
   siteName = siteDescription;

You can write your custom method for doing this.

public int? TryParseNullableValues(string val)
{
    int outValue;
    return int.TryParse(val, out outValue) ? (int?)outValue : null;
}

You can't do this without using another variable, because the type of out arguments has to match the parameter exactly.

 string someStr = "123";
 int? siteNumber = null;

 int tmp;
 if (!int.TryParse(someStr.Trim(), out tmp))
 {
     //Do something if not parsed
 }
 else
 {
     siteNumber = tmp;
 }

The best way is simply use this function to convert string to int no matter it is nullable or not. This custom function will handle it.

public static Int32? CustomConvertToInt32(Object obj)
{
    string _strData = CustomConvertToStringOrNull(obj);

    Int32? _Nullable = null;
    Int32 _data;

    if (Int32.TryParse(_strData, out _data))
    {
        _Nullable = _data;
    }
    return _Nullable;
}

 public static string CustomConvertToStringOrNull(Object obj)
    {
        string _Nullable = null;
        if (obj != null)
        {
            if (obj.ToString().Trim() == "" || obj.ToString().Trim().ToLower() == "n/a")
            {
                _Nullable = null;
            }
            else
            {
                _Nullable = obj.ToString().Trim();
            }
        }

        return _Nullable;
    }


int? siteNumber = CustomConvertToInt32(someStr);

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