Search code examples
c#listgenericsoverload-resolution

Using generic types to call overloaded functions


StreamWrite.Write is overloaded for Int16, Int32, Int64, Double, Single, String and many more.

Why do I need to use dynamic? When calling the WriteList Method, the compiler knows that it is called for Int32, String, ... .
So why can't I use e (of type T=Int32) directly in StreamWrite.Write?

public void WriteList<T>(List<T> list) 
{
  int count = list.Count();
  StreamWriter.Write(count);
  foreach(T e in list) 
  {
    dynamic d = e;
    StreamWriter.Write(d);
  }
}

Solution

  • Because overload resolution (in the absence of dynamic) happens at compile time, and at compile time, the actual type of T is unknown, since generics are a runtime feature.

    The compiler doesn't know which method token of Write to include in the IL when compiling WriteList.