Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }
}
like image 320
bebo Avatar asked Nov 20 '25 03:11

bebo


1 Answers

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.

like image 84
Damien_The_Unbeliever Avatar answered Nov 22 '25 16:11

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!