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 = \"
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.
You do not WANT to make int.TryParse() one line. Why? Because you can't make an assignment to intValue if the input string isn't a valid integer. The whole point of TryParse() is to allow you to test for good input and degrade gracefully, rather than having to catch an exception.
Int.TryParse() is already a shortcut so you don't have to test for a valid int and do the assignment in two steps... that's as far as you want to take it.
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;
}
int val2 = "asd".AsInt(-1);
//Output : -1
int val3 = "123".AsInt(-1);
//Output : 123
You need to have System.Web.WebPages
namespace.