Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whoa, what the TryParse

I've got a Session that contains particular integer values, which are indexed with given controls. Normally, the following would work just fine:

int value;
int.TryParse(Session["Key"].ToString(), out value);

However, I do need to account for null. Where, if the string fails the default out would return a null. Except I noticed that int.TryParse doesn't work with:

int? value = null;
int.TryParse(Session["Key"].ToString(), out value);

So how can you try that parse, if fails it results in the null?

I found this question and the Microsoft Developer Network dictates:

When this method returns, contains the signed integer value equivalent of the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the string parameter is null or String.Empty, is not of the correct format, or represents a number less than Min Value or greater than Max Value. This parameter is passed uninitialized.

Which plainly states, if int.TryParse fails the integer will hold a value of zero. In the instance of my usage, zero could be a valid value. So I need null, any thoughts?

like image 998
Greg Avatar asked Dec 03 '22 18:12

Greg


2 Answers

Sure; utilize the return value of int.TryParse (which returns if the conversion succeeded or not):

int? retValue = null;
int parsedValue = 0;

if (int.TryParse(Session["Key"].ToString(), out parsedValue))
    retValue = parsedValue;
else
    retValue = null;

return retValue;

A little verbose I'll admit, but you could wrap it in a function.

like image 158
BradleyDotNET Avatar answered Dec 12 '22 05:12

BradleyDotNET


int tmp;
int? value = int.TryParse(Session["Key"].ToString(), out tmp) ? (int?)tmp : null;
like image 31
AlexD Avatar answered Dec 12 '22 05:12

AlexD