Start Debugging

generics

1 post

Why can't I cast IDisplayVM<Derived> to IDisplayVM<Base> in C#, and when does out variance fix it?

A class that implements IDisplayVM<DiseaseDTO> does not implement IDisplayVM<IDTO>, so the assignment fails with CS0266, 'as' returns null and an explicit cast throws InvalidCastException. Marking T as 'out' fixes it only if T never appears in an input position; with ICollection<T> or a setter you get CS1961. Reproduced on .NET 11 with the four designs that actually work, benchmarked.