int.TryPrase
is great and all, but there is only one problem...it takes at least two lines of code to use:
int intValue;
string stringValue = \"
Because it essentially returns two values (success and the value), we really do need the two lines.
You could try a wrapper class, ie:
void Main()
{
var result = simpleIntParser.TryParse("1");
if(result)
{
Console.WriteLine((int)result);
} else {
Console.WriteLine("Failed");
}
result = simpleIntParser.TryParse("a");
if(result)
{
Console.WriteLine((int)result);
} else {
Console.WriteLine("Failed");
}
}
public class simpleIntParser
{
public bool result {get; private set;}
public int value {get; private set;}
private simpleIntParser(bool result, int value)
{
this.result = result;
this.value = value;
}
public static simpleIntParser TryParse(String strValue)
{
int value;
var result = int.TryParse(strValue, out value);
return new simpleIntParser(result, value);
}
public static implicit operator int(simpleIntParser m)
{
return m.value;
}
public static implicit operator bool(simpleIntParser m)
{
return m.result;
}
}
It requires casting if the type is ambiguous (i.e. for Console.WriteLine()), but if you pass it as an integer parameter for example, no casting is required
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
I don't think there is anything really beautiful, but if you like this you get it down to one row:
string stringValue = "123"
int intValue = int.TryParse(stringValue, out intValue) ? intValue : 0;
One last addition to this NINE year-old question :). Bool parsing is a little different because if parsing fails, you don't want to return a default value, you want to return a NULL. This line does this (as of C# 7, I think):
return bool.TryParse(value, out bool result) ? (bool?)result : null;
That cast of the result is necessary, otherwise it cannot reconcile the differing types of the two return values.
int intValue = int.TryParse(stringValue, out intValue) ? intValue : 0;
Check out the StringExtensions class. It contains an AsInt(String,Int32) extension method that will attempt to convert a string and if unsuccessful populate it with the supplied Int32 value as default.
Example:
var intValue = "123".AsInt(-1);