user1634494
user1634494

Reputation: 629

How to write a class that can encompass other related classes?

Is it possible to write a class that acts like the super class of two other classes.

For example I have class A and class B. A and B share similar properties, but since I did not code A or B they do not extend an interface or class. Is it possible for me to create this super class so that when I generalize my code it can handle class A or B.

If this super class could be created this is some of what I would like to do in my class

class A
{
    string Name { get; set;}
    //does stuff
    //I can't change this class
}

class B
{
    string Name { get; set;}
    //does similar stuff
    //I can't change this class either
}

class MyClass
{
    //I would like to create a list that can include both class B and class A
    List<(pseudo superclass of A and B)> list;

    //Both class A and class B have a name, I would like to get the name given a type of A or B
    public (pseudo superclass of A and B) GetName((pseudo superclass of A and B) AorB)
    {
        //Write that name to the console
        Console.WriteLine(AorB.Name);
    }

}

Is this kind of wrapping possible, or will I need to do more work inside of MyClass (such as overloading methods) in order to accomplish what I need.

Upvotes: 2

Views: 111

Answers (1)

David Arno
David Arno

Reputation: 43254

I'd suggest,

1 Create an interface:

interface IWrapper
{
    string Name { get; set; }
    ...
}

2 Create wrapper classes:

class WrapperA : IWrapper
{
    private A _a;

    public WrapperA(A a) { _a = a; }

    public Name
    {
        get { return _a.Name; }
        set { _a.Name = value; }
    }
    // other properties here
}

and likewise for a BWrapper around B.

Then you can create your class as:

class MyClass
{
    List<IWrapper> list;

    public string GetName(IWrapper aOrB)
    {
        Console.WriteLine(aOrB.Name);
    }
}

Upvotes: 2

Related Questions