Created
September 30, 2014 13:48
-
-
Save DarranShepherd/35fd20652bd7a68de5f8 to your computer and use it in GitHub Desktop.
Calling a constrained generic method from another generic method without constraints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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