0

I have classes A & B. Both of them share some same parameters x, y, z inherited from abstract class C. Is it possible to make class D that contains List of objects that inherit from class C?

So I can do:

D d = new D();
d.list = new List<A>();

As well as:

D d = new D();
d.list = new List<B>();

Edit: Objects in list have to be modifiable. Following is more precisely described problem:

public abstract class C
    {
        // ...
    }

public class A : C
    {
        // ...
    }

public class D
    {
        public void Method(List<C> list)
        {
            // ...
        }
    }

When I call:

List<A> list = new List<A>();
D d = new D();
D.Method(list);

I get „CS1503: Argument 1: cannot convert from A to C“.

Dženkou
  • 1
  • 3

1 Answers1

0

If you need only readonly operations on the list you can declare it as a covariant collection interface for example IEnumerable or IReadOnlyList:

IReadOnlyList<C> list = new List<A>();
list = new List<B>();
list = new List<C>();

Otherwise there is not much options besides making D a generic class (or using List<C> i.e. List<C> list = new List<C>();).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132