Create method on different class types

There is an option to change the signature of the method to PrintMe(dynamic obj).

At compile time it will accept any object, and only on run time it will check if the obj instance actually has a property that matches. As you can feel, this is quite unsafe and often leads to bugs in production releases.

There isn't really another option. If you can't change the class, but if you can inherit it, you could implement an interface that shares those properties. That only works if you actually create the instances yourself.

Another option would to use a wrapper class:

public string PrintMe(Class1or2Wrapper obj)
{ ... }

Then you implement the logic of determining which property to take there:

public class Class1or2Wrapper
{
    private Class1 c1;
    private Class2 c2;

    public Class1or2Wrapper(Class1 c1)
    {
        this.c1 = c1;
    }

    public Class1or2Wrapper(Class2 c2)
    {
        this.c2 = c2;
    }

    public string AAAAA
    {
        get
        {
            if (this.c1 != null)
                return c1.AAAAA;

            if (this.c2 != null)
                return c2.AAAAA;

            return null;
        }
    }
}

This way you ensure type safety, while limiting the amount of work.


Well, base class of every class is object, so you could hide common implementation as private method:

private string PrintMe( object obj) {
  var instance = obj is MyClass1 ? obj as MyClass1 : obj as MyClass2;

  if(instance == null)
    throw new ArgumentException("Invalid type!");

  string message = "";
  message += instance.AAAAA ;  // this parameter is in both MyClass1 and MyClass2
  message += instance.BBBBB ;  // this parameter is in both MyClass1 and MyClass2
  return message;
}

and expose public API, which will be compile time safe:

public string PrintMe(MyClass1 mc)
{
  return PrintMe(mc as object);
}
public string PrintMe(MyClass2 mc)
{
  return PrintMe(mc as object);
}

Tags:

C#

Types

Class