So I created a custom int.tryparse method in c# to try to make things a little easier and cleaner looking. Here is the method:
public static int? BoolIntParse(string number)
{
int temp;
if (int.TryParse(number, out temp))
return temp;
else
return null;
}
Now, I would like to try to use it in this fashion:
if(int? someNumber = BoolIntParse(someString))
{
//do some stuff if its a number
}
else
//throw some error
Which doesn’t seem to work. I also tried assigning the value before the condtional such as:
int? someNumber = BoolIntParse(someString);
if(someNumber)
{
//do some stuff if its a number
}
else
//throw some error
And I get the error message Cannot implicitely convert type int? to bool
So this isn’t legal c#. Is this what a nullible int was designed for (this type of situation) or am I just not doing it correctly? I’m relatively new to c#.
You want to check if
someNumber.HasValue. That should be in your conditional.if (someNumber.HasValue)or as an alternative, mentioned by @BrokenGlass:
if (someNumber != null)