I need to call method overloads according to the type of object at runtime using c# late binding features. It works fine when all overloads are defined in the same class as the call is happening. But when an overload is defined in a derived class, it won't get bound at runtime.
class BaseT
{}
class DerivedA : BaseT
{}
class DerivedB : BaseT
{}
class Generator
{
public void Generate(IEnumerable<BaseT> objects)
{
string str = "";
foreach (dynamic item in objects)
{
str = str + this.Generate(item); //throws an exception on second item
}
}
protected virtual string Generate(DerivedA a)
{
return " A ";
}
}
class DerivedGenertor : Generator
{
protected virtual string Generate(DerivedB b)
{
return " B ";
}
}
class Program
{
static void Main(string[] args)
{
List<BaseT> items = new List<BaseT>() {new DerivedA(), new DerivedB()};
var generator = new DerivedGenertor();
generator.Generate(items);
}
}
Here is another more clear example:
class BaseT
{}
class DerivedA : BaseT
{}
class DerivedB : BaseT
{}
class DerivedC : BaseT
{ }
class Generator
{
public void Generate(IEnumerable<BaseT> objects)
{
string str = "";
foreach (dynamic item in objects)
{
str = str + this.Generate(item); //throws an exception on third item
}
}
public virtual string Generate(DerivedA a)
{
return " A ";
}
public virtual string Generate(DerivedC c)
{
return " C ";
}
}
class DerivedGenertor : Generator
{
public virtual string Generate(DerivedB b)
{
return " B ";
}
}
class Program
{
static void Main(string[] args)
{
List<BaseT> items = new List<BaseT>() {new DerivedA(), new DerivedC(), new DerivedB()};
dynamic generator = new DerivedGenertor();
generator.Generate(items);
}
}