Skip to content

Instantly share code, notes, and snippets.

@skoon
Created May 10, 2011 06:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skoon/963991 to your computer and use it in GitHub Desktop.
Save skoon/963991 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);
}
@anaisbetts
Copy link

TryParse is usually a Static method, isn't it?

Edit: That's the out parameter, me = dumb

@skoon
Copy link
Author

skoon commented May 10, 2011

Yeah, I probably need to use the binding flags. It seems to work though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment