85

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.

3
  • 2
    The default for int is 0 and is used with an out-parameter, but anyway: stackoverflow.com/a/1078521/284240 May 21, 2012 at 22:03
  • @Tim sometimes it's not type default value, not talking specifically for int, but other data types May 21, 2012 at 22:05
  • @AntonioBakula: Then use Jon Skeets approach in my link and use ref parameter in your own TryParse. May 21, 2012 at 22:06

9 Answers 9

223

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.

6
  • 10
    +1 I must admit that i didn't know that it works in one line. I could have sworn that at least VB.NET doesnt like it, but: Dim i As Int32 = If(Int32.TryParse("nonum", i), i, 42). Thanks. Aug 18, 2014 at 21:36
  • 3
    I like this answer so much!
    – Envil
    Dec 15, 2016 at 10:35
  • 7
    In case you directly want to return the result: return int.TryParse(s, out int i) ? i : 42; Feb 7, 2019 at 13:45
  • 1
    It's a little redundant, though. You only want to perform an additional assignment when TryParse returns false, but the tertiary operator requires you to account for both cases. Apr 24, 2019 at 18:03
  • 2
    Note that the updated version from @BalintPogatsa requries C# 7.0
    – freedomn-m
    Jun 12, 2019 at 17:27
25

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
4
  • I like this more than @skarmats answer, even though probably it's a matter of personal preference May 22, 2012 at 8:34
  • 5
    @AntonioBakula: Yes, preference always matters. However, you won't get type inference on return values. So you will pollute the String-IntelliSense with lots of methods (one for each type you want to parse)
    – skarmats
    May 23, 2012 at 0:04
  • Example implementation here: ericlippert.com/2012/08/14/out-parameters-and-linq-do-not-mix : static int? MyTryParse(this string item) { int tmp; bool success = int.TryParse(item, out tmp); return success ? (int?)tmp : (int?)null; }
    – Jon
    Jan 30, 2017 at 4:51
  • 1
    To save you some typing, here the extension class for most common primitives: hastebin.com/eleyawonex.cs
    – djk
    Jul 13, 2017 at 23:10
14

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

4
13

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

4
  • 7
    Unfortunately declaration expressions didn't make the final cut for C# 6.
    – dav_i
    Feb 9, 2015 at 16:51
  • 1
    @dav_i But we have it now in C# 7! Hallelujah! Mar 16, 2017 at 16:41
  • 4
    @EricSondergard It truly has been a rollercoaster of emotion.
    – dav_i
    Mar 17, 2017 at 10:22
  • 2
    This is nice, but it's still missing the default value. Here we are just avoiding the declaration line.
    – Andrew
    Dec 20, 2018 at 20:20
4

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;
}
3

In your particular example, you can do this:

int value; 
int.TryParse(someStringValue, out value);

...because Int32.TryParse() is documented as setting value=0 if it fails the parse.

1
  • same as comment to Tim: sometimes it's not type default value, not talking specifically for int, but other data types May 21, 2012 at 22:18
1

You could use TypeDescriptor instead:

public T Convert<T>(string input, T defaultVal)
{
    var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
    if(converter != null)
    {
        return (T)converter.ConvertFromString(input);
    }
    return defaultVal;
}

public T Convert<T>(string input)
{
    return Convert(input, default(T));
}

You could constrain T to struct and use Nullable also (as per @skarmats answer).

1
  • You could always use an optional parameter in this case so your first signature reads Convert<T>(string input, T defaultVal = default(T)) and the second method can be removed.
    – dav_i
    Apr 28, 2014 at 13:45
1

I have small enhancement for this answer, which is making an extension method and TryConvert extension method in snippet below:

public static T Convert<T>(this string input, T defaultVal)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));
    if (converter != null)
    {
        return (T) converter.ConvertFromString(input);
    }
    return defaultVal;
}

public static T Convert<T>(this string input)
{
    return Convert(input, default(T));
}

public static bool TryConvert<T>(this string input, T defaultVal, out T result)
{
    try
    {
        result = Convert(input, defaultVal);
        return true;
    }
    catch (Exception exception)
    {
        result = defaultVal;
        return string.IsNullOrEmpty(input);
    }
}

And then we can use it this like a snippet

 if (someValue.TryConvert(1, out var result))
 {

 }

The result data type is automatically depending on defaultVal

0

This is one of the nice surprises for C# developers who try F#. The TryParse method returns a tuple containing both the bool and the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.