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.
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
.
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
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
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 :)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With