tags:

views:

58

answers:

1

Hi!

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?

+3  A: 

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.

Jon Skeet
I'm trying to modify treegridview implementation (derived from ComponentFactory KryptonGridView) to support IList<T> as DataSource (currently only DataTable). And I want to pass to it IList<Producent> or IList<Supplier> and both are derived from ActiveRecordBase<T> class
Adrian Serafin
If it's only for a `DataSource`, then you *could* just expose it as the nongeneric `IEnumerable`, couldn't you? It's leaves a bad taste in the mouth, but it will work.
Jon Skeet