Adrian Serafin
Adrian Serafin

Reputation: 7715

c#, Problem with generic types

I have base class:

class ARBase<T> : ActiveRecordValidationBase<T> where T : class
{
}

and few child classes

class Producent : ARBase<Producent>
{
}

class Supplier : ARBase<Supplier>
{
}

Now in other class I want to have Property of type:

public IList<ARBase<Object>> MyCollection 
{
}

and want to be able to assign collection of Suppliers or collection of Producent, but I'm getting error: can't cast List<Producent> to IList<ARBase<Object>>...

Anyone know solution?

Upvotes: 3

Views: 114

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500504

Basically the problem is that .NET generics don't support covariance like this - there's support in certain cases, but only for interfaces and delegates, and C# only supports it as of version 4. (IList<T> still isn't variant in .NET 4.0 as it uses T in both an "in" and "out" sense.)

As an example of what could go wrong, imagine someone adding a Supplier to a list of Producers - you wouldn't want that to be allowed, but it couldn't be prevented at compile-time if you could convert a List<Producer> to IList<ARBase<object>>.

What do you want your consumers to be able to do with your property? That will suggest how to proceed.

Upvotes: 3

Related Questions