Say I have the following three classes/interfaces:
public interface IImportViewModel
{
}
public class TestImportViewModel : IImportViewModel
{
}
public class ValidationResult<TViewModel> where TViewModel : IImportViewModel
{
}
As TestImportViewModel implements IImportViewModel, why will the following not compile?
ValidationResult<IImportViewModel> r = new ValidationResult<TestImportViewModel>();
I understand what the error message “Cannot implicitly convert type ‘ValidationResult’ to ‘ValidationResult'” means. I just don’t understand why this is the case. Would this not be covariance?
Yes, except that in C# 4.0 covariance works on interfaces only. So you will have to make your
ValidationResultimplement a covariant interface (one for which the generic parameter is defined asout):and now you can do this: