IEnumerable<T>
is co-variant but it does not support value type, just only reference type. The below simple code is compiled successfully:
IEnumerable<string> strList = new List<string>();
IEnumerable<object> objList = strList;
But changing from string
to int
will get compiled error:
IEnumerable<int> intList = new List<int>();
IEnumerable<object> objList = intList;
The reason is explained in MSDN:
Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.
I have searched and found that some questions mentioned the reason is boxing between value type and reference type. But it does not still clear up my mind much why boxing is the reason?
Could someone please give a simple and detailed explanation why covariance and contravariance do not support value type and how boxing affects this?