Skip to content

Instantly share code, notes, and snippets.

@jasonmw
Created May 10, 2011 20:15
Show Gist options
  • Save jasonmw/965287 to your computer and use it in GitHub Desktop.
Save jasonmw/965287 to your computer and use it in GitHub Desktop.
Failover Func
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Jason.Tests {
[TestClass]
public class TryParseTests {
[TestMethod]
public void TestTryParse_Func_Bad() {
Assert.AreEqual(0, "s".TryParse(Failover<int>));
}
[TestMethod]
public void TestTryParse_Func_Zero() {
Assert.AreEqual(0, "0".TryParse(Failover<int>));
}
[TestMethod]
public void TestTryParse_Func_Five() {
Assert.AreEqual(5, "5".TryParse(Failover<int>));
}
public T Failover<T>(string input) {
// try to recover from failed parse here
Console.WriteLine("Did our extra failure work here");
return default(T);
}
}
public static class Helpers {
// adapted from skoon https://gist.github.com/963991
public static duck TryParse<duck>(this string stringToParse, Func<string,duck> failover) {
if (typeof(duck).HasMethod("TryParse")) {
var m = typeof(duck).GetMethod("TryParse", new Type[] { typeof(string), typeof(duck).MakeByRefType() });
duck outParam = Activator.CreateInstance<duck>();
object[] ps = new object[] { stringToParse, outParam };
bool result = (bool)m.Invoke(null, ps);
if (result)
return (duck)ps[1];
}
return failover(stringToParse);
}
private static bool HasMethod(this Type type, string methodName) {
var m = type.GetMethods();
return (m.Any(x => x.Name == methodName));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment