6

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?

devlife
  • 15,275
  • 27
  • 77
  • 131
  • 2
    I'm assuming your class _TestImportViewModel_ is supposed to be _TViewModel_? (The code above does not show class TViewmModel at all). – Sam Goldberg Jul 02 '12 at 13:23
  • Yes. TestImportViewModel implements IImportViewModel and thus __should__ be able to be used as a TViewModel implementation as TViewModel : IImportViewModel. – devlife Jul 02 '12 at 13:28
  • 3
    @Sam TViewmModel(aka ) is a type of IImportViewModel its not a class . – Renatas M. Jul 02 '12 at 13:28
  • 1
    @SamGoldberg, It's the generic parameter, often seen as `T` but in this case has a much more descriptive name. – Filip Ekberg Jul 02 '12 at 13:28
  • 1
    [Here is](http://stackoverflow.com/a/4653199/540345) a explanation of similar problem. – NaveenBhat Jul 02 '12 at 13:37

1 Answers1

8

Would this not be covariance?

Yes, except that in C# 4.0 covariance works on interfaces only. So you will have to make your ValidationResult implement a covariant interface (one for which the generic parameter is defined as out):

public interface IImportViewModel
{
}

public class TestImportViewModel : IImportViewModel
{
}

public interface IValidationResult<out TViewModel> where TViewModel : IImportViewModel
{
}

public class ValidationResult<TViewModel> : IValidationResult<TViewModel> where TViewModel : IImportViewModel 
{
}

and now you can do this:

IValidationResult<IImportViewModel> r = new ValidationResult<TestImportViewModel>();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928