C# extension method resolves to wrong class

Viewed 38

Consider this code:

public static class Class1
{
    public static string Test(this string t) => "string";
    public static string Test<T>(this T t) => "t";
    public static string Test<U>(this List<U> list)
    {
        StringBuilder result = new StringBuilder();
        list.ForEach(s => result.Append($"{s.Test()},"));
        return $"List({result.ToString()})";
    }

    public static void X()
    {
        System.Diagnostics.Debug.WriteLine("Hallo".Test()); // "string"
        System.Diagnostics.Debug.WriteLine(new Y().Test()); // "t"
        var YList = new List<Y>();
        YList.Add(new Y());
        System.Diagnostics.Debug.WriteLine(YList.Test());   // "List(t,)"
        var stringList = new List<string>();
        stringList.Add("Hallo");
        System.Diagnostics.Debug.WriteLine(stringList.Test());  // "List(t,)" !!
    }
}

IMO the last case should output "List(string,)" because it is called for a List<string> and there is a more specific extension method string.Test(). What am I doing wrong? How to solve this problem?

0 Answers
Related