Why can't this generic type be converted?

Let's say I have the following three classes / interfaces:

public interface IImportViewModel { } public class TestImportViewModel : IImportViewModel { } public class ValidationResult<TViewModel> where TViewModel : IImportViewModel { } 

How TestImportViewModel implements IImportViewModel, why the following does not compile?

 ValidationResult<IImportViewModel> r = new ValidationResult<TestImportViewModel>(); 

I understand that the error message โ€œIt is not possible to implicitly convert the typeโ€œ ValidationResult โ€toโ€œ ValidationResult "means. I just donโ€™t understand why this is so. Would it be covariance?

+6
source share
1 answer

Could this be covariance?

Yes, except that in C # 4.0 covariance only works with interfaces. Thus, you must make your ValidationResult implement a covariant interface (one for which the general 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>(); 
+8
source

Source: https://habr.com/ru/post/919503/


All Articles