Coder Perfect

How do you convert a string to a nullable int?


In C#, I’d like to convert a string to a nullable int. I’d like to retrieve either the string’s int value or null if it can’t be parsed.

I was hopeful that things would work out.

int? val = stringVal as int?;

But it isn’t going to work, so I’ve built this extension method instead.

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

Is there a more efficient method to do this?

EDIT: Thanks for the TryParse suggestions; I was aware of those, but they worked out similarly. I’m more curious as to whether there is a built-in framework mechanism for parsing directly into a nullable int.

Asked by Glenn Slaven

Solution #1

int.TryParse is arguably a little more straightforward:

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

Int.TryParse is “integrated into the framework,” according to @Glenn. The methods for parsing strings to ints are It and int.Parse.

Answered by Matt Hamilton

Solution #2

You can do this in one line by using the conditional operator and the fact that you can cast null to a nullable type (two lines if you don’t have an int you can reuse for TryParse output):

Pre C#7:

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

This is made even easier by C#7’s revised syntax, which allows you to define an output variable in the method call.

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

Answered by McKenzieG1

Solution #3

[As suggested by @sblom, updated to utilize contemporary C#]

I ran into this issue and came up with the following solution (after all, an if and two returns is so long!):

int? ToNullableInt (string val)
    => int.TryParse (val, out var i) ? (int?) i : null;

On a more serious note, avoid mixing int, which is a C# keyword, with Int32, which is a.NET Framework BCL type – it works, but it looks cluttered.

Answered by Duckboy

Solution #4

var result = int.TryParse(foo, out var f) ? f : default;

To find out which language version your project supports, go up C# language versioning.

Answered by Jaa H

Solution #5

If the value is valid, such as null or empty string, there is a way that will parse directly to a nullable int (and not simply int), but it will throw an exception if the value is invalid, therefore you’ll need to catch the exception and return the default value:

public static T Parse<T>(object value)
    try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }
    catch { return default(T); }

This method can be used for both nullable and non-nullable parses:

enum Fruit { Orange, Apple }
var res1 = Parse<Fruit>("Apple");
var res2 = Parse<Fruit?>("Banana");
var res3 = Parse<int?>("100") ?? 5; //use this for non-zero default
var res4 = Parse<Unit>("45%");

NB: Instead of capturing the exception, you can utilize the converter’s IsValid method (thrown exceptions does result in unnecessary overhead if expected). Unfortunately, it only works since.NET 4, and there is still a fault 93559 where it fails to check your locale when validating accurate DateTime formats.

Answered by Michael

Post is based on