First, forget / do not know that the TryParse method (and not TryXXX by the way) returns a bool telling you whether the conversion succeeded. The method that returns the resulting conversion value is called Parse. For example:
int res = Int32.Parse("123");
Secondly, your example
if(Int32.TryParse("10") != null)
wrong How do you think it should return an int (value-type) in one case and a null in the other (clearly indicating a reference-type)?
However, you can write an extension matod to help solve the inconvenient syntax problem:
namespace MyExtensions { public static class ParseExtender { public static int? ParseInt(this string source) { int res; return Int32.TryParse(source, out res) ? (int?)res : null; } } }
And if you really want versatility at all, you can do it like this:
namespace MyExtensions { public static T? RightParse<T>(this string input) where T : struct { var converter = TypeDescriptor.GetConverter(typeof(T)); try { return (T?)converter.ConvertFromString(null, CultureInfo.InvariantCulture, input); } catch (Exception) { return null; } } }
Use this:
Console.WriteLine("256".RightParse<int>() ?? -1); Console.WriteLine("256.2".RightParse<double>() ?? -1); Console.WriteLine("true".RightParse<bool>() ?? false);
Just remember to add using MyExtensions to use it all.