I have noticed an unexpected behavior while trying to extend a base class. Here is a sample for this problem:
public class Program
{
static void Main(string[] args)
{
var test = new CoolProgram();
test.Start();
}
private void Start()
{
var arr = new object[]
{
1, // int
1L, // long
"Hello World" // string
};
foreach (var dyn in arr.Cast<dynamic>())
{
DoSomething(dyn);
}
Console.ReadKey();
}
protected virtual void DoSomething(int i)
{
Console.WriteLine("Int:" + i);
}
protected virtual void DoSomething(string str)
{
Console.WriteLine("Str:" + str);
}
}
The Program defines two methods DoSomething which are overloaded by int and string arguments. The Start method creates an array of objectwhich contains boxed values. After the definition, the elements will be iterated with casteddynamic`. This works fine so far (without the long value).
If I create an additional inherited class CoolProgram and add another method to the type for long the program will throw an RuntimeBinderException and tells me that the best overload was DoSomething(int). The method of CoolProgram was not executed.
public class CoolProgram : Program
{
protected override void DoSomething(int i)
{
// This works
Console.WriteLine("Cool Int: " + i);
}
protected override void DoSomething(string str)
{
// This works
Console.WriteLine("Cool Str: " + str);
}
protected virtual void DoSomething(long i)
{
// This is a new method for long
Console.WriteLine("Long:" + i);
}
}
Can anybody explain this behavior or have a solution for it?
dynamicjust defers type resolution and subsequent compilation steps to runtime. So what you're really asking is why overload resolution does what it's doing.