Skip to content

Instantly share code, notes, and snippets.

@Larry57
Last active October 11, 2015 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Larry57/3910180 to your computer and use it in GitHub Desktop.
Save Larry57/3910180 to your computer and use it in GitHub Desktop.
Universal TryParse
public class DuckTryParse
{
public static bool TryParse<duck>(string stringToParse, out duck value)
{
var method = MethodCache<duck>.TryParse;
if (method == null || !method(stringToParse, out value))
{
value = default(duck);
return false;
}
return true;
}
delegate bool TryParseSignature<duck>(string value, out duck result);
class MethodCache<duck>
{
public static readonly TryParseSignature<duck> TryParse;
static MethodCache()
{
var method = typeof(duck).GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), typeof(duck).MakeByRefType() }, null);
if (method != null)
TryParse = (TryParseSignature<duck>)Delegate.CreateDelegate(typeof(TryParseSignature<duck>), method);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment