I am struggling to get the correct extension methods called in generic methods.
I guess it is a limitation of compile time method picking but is there a clever way around this in C#?
[TestClass]
public class WrongOverloadSelection
{
[TestMethod]
public void WorksNew()
{
new Generic<A>().Test();
}
[TestMethod]
public void FailsGeneric()
{
PicksWrongOverload<A>();
}
public void PicksWrongOverload<T>()
{
new Generic<T>().Test();
}
}
public class A{}
public class Generic<T>{}
public static class Extensions
{
public static void Test(this Generic<A> source) { }
public static void Test<T>(this Generic<T> source)
{
throw new Exception("Not this one!");
}
}
Try this:
// Now it picks then right one
public static void PicksWrongOverload<T>()
{
Extensions.Test((dynamic)new Generic<T>());
}
The reason for this is explained here, but essentially at runtime the CLR will convert the dynamic type to the required type of the routine, and if there is nothing happening that violates the type checking rules then you are good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With