Search code examples
c#.netclassdynamicduck-typing

two class with common methods and properties


I have two classes.

Class A:

class A() {
    public void QQ() {}
    public void WW() {}
}

And Class B:

class B() {
    public void QQ() {}
    public void WW() {}
}

They don't share the same interface or abstract class. A and B have two distinct hierarcy and I can't change that at the moment.

I want to write a single procedute that works for A and B and use QQ and WW methods.

Can I do that? Can you suggest any document I can study?

Tanks


Solution

  • This is called Duck Typing.

    You can use dynamics

    void Foo(dynamic dy)
    {
        dy.QQ();
    }
    

    You can also use reflection. (reference)

    public static void CallQQ(object o)
    {
        var qq = o.GetType().GetMethod("QQ");
        if (qq != null)
            qq.Invoke(o, new object[] { });
        else
            throw new InvalidOperationException("method not found");
    }