Hello,
I have a set of classes which I didn't write, and they're read only. Let's say, for the example, that those classes are the following ones:
public class Base { }
public class B : Base { }
public class C : B { }
public class D : Base { }
I want to add a method Foo() on all these classes, I am using extension methods:
public static class Extensions {
public static void Foo(this Base obj) {
dynamic dynobj = obj;
try {
dynobj.Foo();
}
catch (RuntimeBinderException ex) {
Console.WriteLine(ex.Message);
}
}
public static void Foo(this B b) {
Console.WriteLine("Foo in B");
}
public static void Foo(this C c) {
Console.WriteLine("Foo in C");
}
}
As you can see, I'm trying to use the keyword dynamic, expecting it know the real type of my object and call its Foo() method. But... dynobj.Foo() always fails.
static void Main(string[] args) {
List<Base> list = new List<Base>();
list.Add(new B());
list.Add(new C());
list.Add(new D());
list.ForEach(x => x.Foo());
}
I know I could use the Adaptor pattern, but I really have too many classes.
Is it a good idea to do that with dynamic? Is it possible to make this work?
Thank you.