Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 437
Michael Avatar asked Oct 29 '25 14:10

Michael


2 Answers

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;
}
like image 60
mybirthname Avatar answered Nov 01 '25 03:11

mybirthname


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;
like image 34
Julian Avatar answered Nov 01 '25 04:11

Julian