Skip to content

Instantly share code, notes, and snippets.

@thzinc
Created March 3, 2016 01:45
Show Gist options
  • Save thzinc/82f9b4b22361742bc87b to your computer and use it in GitHub Desktop.
Save thzinc/82f9b4b22361742bc87b to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace Sonorous.Core.Services
{
public static class StructExtensions
{
public delegate bool TryParseDelegate<T>(string input, out T value);
public static T? TryParse<T>(this string input)
where T : struct
{
var methodInfo = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(mi => mi.Name == "TryParse" && mi.GetParameters().Length == 2);
if (methodInfo == null)
return null;
var selector = (TryParseDelegate<T>)methodInfo.CreateDelegate(typeof(TryParseDelegate<T>));
return input.TryParse(selector);
}
public static T? TryParse<T>(this string input, TryParseDelegate<T> selector)
where T : struct
{
T result;
if (selector(input, out result))
return result;
return null;
}
public static IEnumerable<T?> AsNullable<T>(this IEnumerable<T> items)
where T : struct
{
return items.Cast<T?>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment