What is Variance and how do I ~deal~ work with it?

  • Page Owner: Not Set
  • Last Reviewed: 2020-01-14

I'm having issues with Variance, how can I better understand variance in C#?


Additional Posts

Variance

Variance is the concept of how inheriting classes are related. Much like a parent/child relationship, it's complicated.

Example source

// IPageModel.cs
public interface IPageModel<T> 

// IPage.cs
public interface IPage 
   
// BasePage.cs
public class BasePage : IPage

// BlogPage.cs
public class BlogPage : BasePage

Invariance ????

Invariance does not allow any variance. IPageModel<BasePage> Can ONLY accept type argument of BasePage

Covariance - out keyword ????

Covariance allows for those that inherit from the specified type

Given the following: IPage<out T> This can accept type argument of T or anything that inherits T. IPage<>

Contravariance - in keyword ????

Contravariance allows for those that do not implement, but are inherited by the type IPage<in T> Can accept type argument of BasePage or anything that inherits base page.