-
-
Save atifaziz/964022 to your computer and use it in GitHub Desktop.
First crack at trying a generic TryParse method.
This file contains 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment