tags:

views:

47

answers:

2

Hello

I'm trying to do the following:

List<IRepository<IBusinessObject, ICriteria>> Repositories { get; }

and call this by

IRepository<ICustomer, ICustomerCriteria> cr = new CustomerRepository();

List.Add(CustomerRepository);

where ICustomer and ICustomerCriteria descend from IBusinessObject and ICriteria respectively.

However, this is not liked by the compiler.

Hmmm, I know I'm pushing it a bit, but I thought this would work? Anyone know why?

Thanks Duncan

+3  A: 

C# doesn't support covariance for generics. Consider this Covariance and Contravariance in C#, Part One

Dzmitry Huba
+1  A: 

This is a generic variance problem:

This will illustrate the issue:

List<string> Strings = ...;
List<object> Objects = Strings; // Should work

Objects.Add(42); // 42 is an object - Should work
// But we would add an integer into a list of strings!!

In .NET FX 4, C# will support a special kind of in and out generic parameters to allow correct behavior.

Dario
Okay, but my object graph is sound - ICustomer descends from IBusinessObject, so I still don't see the problem! Hmmm... any recommended workarounds then?
Duncan
But you could add an `ICompletelyDifferentCriteria` into your list of `ICustomerCriteria` since both inherited `ICriteria`.
Dario