user2707674 user2707674 - 3 months ago 6
C# Question

Call any class sharing the same method name in C#

I have a significant number of classes which share the same method name, but don not share a common base/interface. I cannot touch these classes, however, can I call the method irrespective of the defining class?

Eg:

Namespace n1: class A { void M1(n1.CustObj ob1){} }
Namespace n2: class B { void M1(n2.CustObj ob1){} }


Would it be possible to abstract from these common methods/parameters, like so?

method(Object obj)
{
obj.M1(new CustObj() {
x = 3;
}); // CustObj can either belong to n1 or n2
}

Answer

You have a number of classes, each of which has a method, with the same name, but with a different signature. The identical method names are a red herring here therefore as they are different methods.

This therefore rules out using dynamic or reflection to provide a single method that can handle all of them, unless you then hard-code tests for each type within the one method, or take Jonathan Wood's approach of passing in an existing instance of CustObj via a dynamic parameter too.

One solution might be to create extension methods for each type:

public void Method(this A obj)
{
    obj.M1(new n1.CustObj()
    {
        x = 3
    }); 
}

public void Method(this B obj)
{
    obj.M1(new n2.CustObj()
    {
        x = 3
    }); 
}

and so on. Then at least you can do someObj.Method(); on A, B and so forth.