Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant TryParse

Tags:

c#

I feel that every time I use TryParse that it results in somewhat ugly code. Mainly I am using it this way:

int value;
if (!int.TryParse(someStringValue, out value))
{
    value = 0;
}

Is there some more elegant solution for parsing all basic data types, to be specific is there a way to do fail safe parsing in one line? By fail safe I assume setting default value if parsing fails without exception.

By the way, this is for cases where I must do some action even if parsing fails, just using the default value.

like image 493
Antonio Bakula Avatar asked May 21 '12 21:05

Antonio Bakula


5 Answers

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.

like image 86
dav_i Avatar answered Nov 20 '22 07:11

dav_i


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
like image 21
user287107 Avatar answered Nov 20 '22 06:11

user287107


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

like image 14
skarmats Avatar answered Nov 20 '22 06:11

skarmats


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 :)

like image 13
Antonio Bakula Avatar answered Nov 20 '22 05:11

Antonio Bakula


using C# 7 in single line

int.TryParse(s, out var i) ? i : (int?)null;

Example Method:

public static int? TryParseSafe(string s)
{
    return int.TryParse(s, out var i) ? i : (int?)null;
}
like image 4
Francesco Moroni Avatar answered Nov 20 '22 06:11

Francesco Moroni