Created
May 10, 2011 06:16
-
-
Save skoon/963991 to your computer and use it in GitHub Desktop.
First crack at trying a generic TryParse method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
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
TryParse is usually a Static method, isn't it?
Edit: That's the out parameter, me = dumb