Skip to content

Instantly share code, notes, and snippets.

@DarranShepherd
Created September 30, 2014 13:48
Show Gist options
  • Save DarranShepherd/35fd20652bd7a68de5f8 to your computer and use it in GitHub Desktop.
Save DarranShepherd/35fd20652bd7a68de5f8 to your computer and use it in GitHub Desktop.
Calling a constrained generic method from another generic method without constraints
namespace ExploratoryUnitTests
{
using Machine.Specifications;
public interface IFoo
{
}
public interface IBar : IFoo
{
}
public class GenericConstraintsWithReflection
{
public bool UnconstrainedMethod<T>()
{
if (typeof(IFoo).IsAssignableFrom(typeof(T)))
{
var methodInfo = this.GetType().GetMethod("ConstrainedMethod").MakeGenericMethod(typeof(T));
return (bool)methodInfo.Invoke(this, null);
}
return false;
}
public bool ConstrainedMethod<T>() where T : IFoo
{
return true;
}
}
[Subject(typeof(GenericConstraintsWithReflection))]
public class GenericConstraintsWithReflectionOnObject
{
static bool result;
Because of = () => result = new GenericConstraintsWithReflection().UnconstrainedMethod<object>();
It should_be_false = () => result.ShouldBeFalse();
}
[Subject(typeof(GenericConstraintsWithReflection))]
public class GenericConstraintsWithReflectionOnIFoo
{
static bool result;
Because of = () => result = new GenericConstraintsWithReflection().UnconstrainedMethod<IFoo>();
It should_be_true = () => result.ShouldBeTrue();
}
[Subject(typeof(GenericConstraintsWithReflection))]
public class GenericConstraintsWithReflectionOnIBar
{
static bool result;
Because of = () => result = new GenericConstraintsWithReflection().UnconstrainedMethod<IBar>();
It should_be_true = () => result.ShouldBeTrue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment