Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick the correct c# overloaded extension method called from a generic method

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!");
    }
}
like image 267
Tom Deloford Avatar asked Sep 12 '25 12:09

Tom Deloford


1 Answers

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.

like image 188
Carson Avatar answered Sep 14 '25 03:09

Carson