Greg Greg - 1 year ago 103
ASP.NET (C#) Question

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
fails the default out would return a
. Except I noticed that
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
fails the integer will hold a value of zero.
In the instance of my usage, zero could be a valid value. So I need
, any thoughts?

Answer Source

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;
    retValue = null;

return retValue;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download