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);
"Objects".Dump();
ToString<object>(list2);
"Longs".Dump();
ToString<long>(list3);
}
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 + "'";
}
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,
source
share