Skip to content

Instantly share code, notes, and snippets.

@dasjestyr
Last active April 30, 2017 20:01
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 dasjestyr/90d8ef4dea179a6e08ddd85e0dacbc94 to your computer and use it in GitHub Desktop.
Save dasjestyr/90d8ef4dea179a6e08ddd85e0dacbc94 to your computer and use it in GitHub Desktop.
public class TryParseFactory
{
public delegate bool TryParseDelegate<T>(string s, out T result);
private readonly Dictionary<Type, Delegate> _tryParsers = new Dictionary<Type, Delegate>();
public TryParseFactory()
{
Register<Guid>(Guid.TryParse);
Register<int>(int.TryParse);
Register<uint>(uint.TryParse);
Register<long>(long.TryParse);
Register<ulong>(ulong.TryParse);
Register<decimal>(decimal.TryParse);
Register<double>(double.TryParse);
Register<float>(float.TryParse);
}
public void Register<T>(TryParseDelegate<T> d)
{
_tryParsers[typeof(T)] = d;
}
public bool Deregister<T>()
{
return _tryParsers.Remove(typeof(T));
}
public bool TryParse<T>(string s, out T result)
{
if (!_tryParsers.ContainsKey(typeof(T)))
{
throw new ArgumentException("Does not contain parser for " + typeof(T).FullName + ".");
}
var d = (TryParseDelegate<T>)_tryParsers[typeof(T)];
return d(s, out result);
}
public bool TryParse(Type type, string s, out object result)
{
if (!_tryParsers.ContainsKey(type))
{
throw new ArgumentException("Does not contain parser for " + type.FullName + ".");
}
var method = GetType().GetTypeInfo()
.GetDeclaredMethods("TryParse")
.First(m => m.IsGenericMethod)
.MakeGenericMethod(type);
object outParameter = null;
var arguments = new[] { s, outParameter };
var parseSucceeded = (bool) method.Invoke(this, arguments);
result = arguments[1];
return parseSucceeded;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment