int.TryParse syntatic sugar
int intValue = int.TryParse(stringValue, out intValue) ? intValue : 0;
Maybe use an extension method:
public static class StringExtensions
{
public static int TryParse(this string input, int valueIfNotConverted)
{
int value;
if (Int32.TryParse(input, out value))
{
return value;
}
return valueIfNotConverted;
}
}
And usage:
string x = "1234";
int value = x.TryParse(0);
Edit: And of course you can add the obvious overload that already sets the default value to zero if that is your wish.
I would create an extension method out of this.
public static int? AsInt32(this string s)
{
int value;
if (int.TryParse(s, out value))
return value;
return null;
}
This answer is only for those who use at least C# 7.
You can now declare the out parameter inline.
int.TryParse("123", out var result);
Exemplary usage:
if (int.TryParse("123", out var result)) {
//do something with the successfully parsed integer
Console.WriteLine(result);
} else {
Console.WriteLine("That wasn't an integer!");
}
MSDN: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables