Elegant TryParse

This is valid and you may prefer it if you have a liking for single-liners:

int i = int.TryParse(s, out i) ? i : 42;

This sets the value of i to 42 if it cannot parse the string s, otherwise it sets i = i.


You can write your own methods for a solution that suits you better. I stumbled upon the Maybe class that wraps the TryParse methods a while ago.

int? value = Maybe.ToInt("123");

if (value == null)
{
    // not a number
}
else
{
    // use value.Value
}

or specify the default value in-line:

int value = Maybe.ToInt("123") ?? 0;

Observe the distinction between Nullable<int>/int? and int.

See http://www.kodefuguru.com/post/2010/06/24/TryParse-vs-Convert.aspx for more info


how about a direct extension method?

public static class Extensions
{
    public static int? TryParse(this string Source)
    {
        int result;
        if (int.TryParse(Source, out result))
            return result;
        else

            return null;
    }
}

or with the new c# syntax in a single line:

public static int? TryParse(this string Source) => int.TryParse(Source, out int result) ? result : (int?)null;

usage:

v = "234".TryParse() ?? 0

There is a nice little feature in C# 6 C# 7, Declaration expressions, so in C# 7 instead of:

int x;
if (int.TryParse("123", out x))
{
  DoSomethingWithX(x);
}

we can use:

if (int.TryParse("123", out int x))
{
  DoSomethingWithX(x);
}

Nice enough for me :)

Tags:

C#