Software Architecture – C# 4.0 – Dynamic type – Compile time polymorphism / Method Overloading

With reference to previous post at here about Dynamic Type, lets do some exploration with reference to Overloaded Methods.
Compile time polymorphism or Overloading resolution is performed at compile time, but incase of a dynamic type as argument, it is done at run time. That is very important method to note.
Consider a simple method as:

public void  DoSomething(string str){}

Some test case will be as with reference to overloading of methods.

string strVar = "Hello";
int intVar = 5;
dynamic dynVar;
// Test Case 1:            
DoSomething(strVar);

// Test Case 2:
// Compile time error that overloaded method has some invalid arguments
// DoSomething(1); 

//TestCase 3
// Works fine in compile time and run time , as dynVar Takes type of string in  run time
dynVar = strVar;
DoSomething(dynVar);

// Test Case 4
// Works in compile time as dynVar can take any type,so can also take string type. But as dynVar takes the type of int, so gives a invalid argument exeception in run time.
dynVar = intVar;
DoSomething(dynVar);

Leave a comment