Michael Michael - 1 year ago 97
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))
{ }
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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download