Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Casting Generic Type

Tags:

c#

I have a generic interface IConstrained which is implemented by the generic Constrained class. When I attempt to do the code below I get an invalid cast exception.

IConstrained<decimal> decimalLimit = new Constrained<decimal>(1);
IConstrained<IComparable> comparableLimit = (IConstrained<IComparable>) decimalLimit;

Why is it not possible to do this if decimal implements IComparable? What would be the correct way to do this? Thanks.

like image 893
RFBoilers Avatar asked Jun 05 '26 21:06

RFBoilers


1 Answers

Generic types are not covariant in .NET 2.0. This includes .NET 3.0/3.5 as well since they use the same 2.0 runtime. .NET 4.0 will support covariance, however.

like image 179
bobbymcr Avatar answered Jun 07 '26 10:06

bobbymcr