Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Forked from skoon/GenericTryParse.cs
Created May 10, 2011 06:52
Show Gist options
  • Save atifaziz/964022 to your computer and use it in GitHub Desktop.
Save atifaziz/964022 to your computer and use it in GitHub Desktop.
First crack at trying a generic TryParse method.
public static T TryParse<T>(this string stringToParse) {
if (typeof(T).HasMethod("TryParse")) {
var m = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });
T outParam = Activator.CreateInstance<T>();
object[] ps = new object[] { stringToParse, outParam };
bool result = (bool)m.Invoke(null, ps);
if (result)
return (T)ps[1];
}
return default(T);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment