bebo
bebo

Reputation: 839

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);
  }
}

Upvotes: 3

Views: 109

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

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.

Upvotes: 7

Related Questions