Michael Michael - 1 month ago 10
C# Question

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?

Answer

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;
}