views:

153

answers:

2

I have the following classes defined to do validation:

public class DefValidator : IValidate<IDef>
{
}

public interface IDef : IAttribute
{
}

Then, I have a list of validators defined as so:

IList<IValidate<IAttribute>> ValidationObjects;

When I try the following, it doesn't compile saying it can't convert types.

DefValidator defv = new DefValidator();
ValidationObjects.Add(defv);

When I try the following, it compiles but generates an exception saying "unable to cast object".

ValidationObjects.Add((IValidate<IAttribute>)defv);

Any ideas?

+4  A: 

Your problem is to do with covariance/contravariance, see http://stackoverflow.com/questions/245607/how-does-c-4-0-generic-covariance-contra-variance-implmeneted

KeeperOfTheSoul
+1  A: 

This is a subtle issue to do with co and contra-variance in generics; there are many simpler examples of this on SO. Essentially, types within generics have to match exactly to be compatible, they can't be subclasses or superclasses.

To get it to compile, ValidationObjects needs to be IList<IValidate<IDef>>, or DefValidator needs to inherit off IValidate<IAttribute>

thecoop