How to parse a string into a nullable int

I'm intending to parse a string right into a nullable int in C#. ie. I intend to come back either the int value of the string or null if it can not be analyzed.

I was sort of wishing that this would certainly function

int? val = stringVal as int?;

But that will not function, so the means I'm doing it currently is I've created this expansion method

public static int? ParseNullableInt(this string value)
{
    if (value == null || value.Trim() == string.Empty)
    {
        return null;
    }
    else
    {
        try
        {
            return int.Parse(value);
        }
        catch
        {
            return null;
        }
    }
}   

Is there a far better means of doing this?

EDIT: Thanks for the TryParse pointers, I did find out about that, yet it exercised concerning the very same. I'm extra curious about recognizing if there is a constructed - in structure method that will parse straight right into a nullable int?

335
2022-06-08 02:52:47
Source Share
Answers: 4

You need to never ever make use of an exemption if you do not need to - the expenses is dreadful.

The variants on TryParse address the trouble - if you intend to get imaginative (to make your code look even more classy) you can possibly do something with an expansion method in 3.5 yet the code would certainly be essentially the very same.

0
2022-06-08 03:19:53
Source

Try this:

public static int? ParseNullableInt(this string value)
{
    int intValue;
    if (int.TryParse(value, out intValue))
        return intValue;
    return null;
}
10
2022-06-08 02:54:06
Source

int.TryParse is possibly a bit less complicated:

public static int? ToNullableInt(this string s)
{
    int i;
    if (int.TryParse(s, out i)) return i;
    return null;
}

Edit @Glenn int.TryParse is "built right into the framework". It and also int.Parse are the means to parse strings to ints.

385
2022-06-08 02:53:59
Source

You can do this in one line, making use of the conditional driver and also the reality that you can cast null to a nullable type (2 lines, if you do not have a pre - existing int you can recycle for the result of TryParse):

Pre C# 7:

int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;

With C# 7 is upgraded syntax that permits you to proclaim a result variable in the method call, this gets back at less complex.

int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;
208
2022-06-08 02:53:59
Source