Pimeko
Pimeko

Reputation: 73

Create an object with an inherited object as a parameter

I have a problem concerning inheritance and constructor in C#.

Indeed, I created a class Elements and classes which inherits from it, like Window or Message.

At some point, I wanted another class to use, in its constructor, a List of Elements so that it can use both Windows and Messages. However, when I create my new object, it requires only the base type, Elements.

I thus can not create something like :

obj = new Obj(List<Window> w)

It just allows

obj = new Obj(List<Elements> e)

I really don't know what it the problem. I tried to set the Elements class as abstract because I will never need to create an object "Element", but it still doesn't work.

If someone could help it would be really nice :) Thanks !

Upvotes: 0

Views: 113

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

List<T> is not covariant, so if your constructor expects List<BaseClass> you cannot pass List<DerivedClass>.

Use IEnumerable<BaseClass> instead, to get covariance.

Or make your class generic, with generic constraint:

public class MyClass<T> where T : Element
{
    public MyClass(List<T> items)
    {

    }
}

Upvotes: 2

Related Questions