An overloaded method with a string parameter is never called; instead, a method with an object parameter is called

I don’t understand why the method is Value(string s)never called for elements List<string>when the list is passed to the method ToString<M>(List<M> list). Below is my test code extracted from LinqPad.

I have no problem calling the proper method Value(), iterating through lists outside the method ToString<M>(List<M> list).

Thanks!

void Main()
{
    var list1 = new List<string>{"one","two","three"};
    var list2 = new List<object>{1,2,3};
    var list3 = new List<long>{1,2,3};
    "Strings".Dump();
    ToString<string>(list1);
    //list1.ForEach(i=> Value(i)); // proper overload of Value() is called 
    "Objects".Dump();
    ToString<object>(list2);
    //list2.ForEach(i=> Value(i));
    "Longs".Dump();
    ToString<long>(list3);
    //list3.ForEach(i=> Value(i));
}

public static string ToString<M>(List<M> list) 
{

    var sb = new StringBuilder();
    foreach(M i in list)
    {
        sb.AppendFormat("{0},", Value(i));
    }
    var str = sb.ToString();
    str.Dump();
    return str;
}


public static string Value(string s)
{
    "String".Dump();
    return "'" + s + "'";
}

// Define other methods and classes here
public static string Value(object o)
{
    "Object".Dump();
    return o.ToString();
}

Here is the result. It shows that the value (string s) is never called

Strings
Object
Object
Object
one,two,three,
Objects
Object
Object
Object
1,2,3,
Longs
Object
Object
Object
1,2,3,
+4
source share
1 answer

Value() ToString<M> . M , , , Value(object).

Value(string), string, i dynamic foreach:

foreach(dynamic i in list)
{
    sb.AppendFormat("{0},", Value(i));
}

Value(i) , , string object.

+6

All Articles