C # Casting Generic Type

I have a common IConstrained interface that is implemented by the common Constrained class. When I try to make the code below, I get an invalid cast exception.

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

Why is this impossible to do if decimal implements IComparable? What would be the right way to do this? Thanks.

+3
source share
7 answers

Generic types are not covariant in .NET 2.0. Including .NET 3.0 / 3.5, as they use the same runtime. .NET 4.0 will support covariance .

+7
source

Casting IConstrained <decimal> in IConstreined <IComparable> is called covariance. You cannot do this in C # 3. However, it is included in C # 4.

, .

, IComparable, .

+4

# ( Generics).

# (, ). IConstrained<IComparable> , IConstrained<decimal>, decimal IComparable. , # , , , .

, ,

+1

, , IConstrained<decimal> and IConstrained<IComparable>

class A:IConstrained<decimal>,IConstrained<IComparable>

, .NET 2.0 . IConstrained<decimal> IConstrained<IComparable>. , . # 4.0 , . .

: familier Constrained, Contrained<IComparable> . Constrained<T> (T copyFrom), Constrained<IComparable> . .

2: , "2.0", , .NET 2.0: http://blog.t-l-k.com/dot-net/2009/c-sharp-4-covariance-and-contravariance

+1

" ".

IList<decimal> decimalLimit = new List<decimal>(1);
IEnumerable<IComparable> asComparable = decimalLimit.Cast<IComparable>();
IList<IComparable> comparableLimit = asComparable.ToList();
+1

, . :

IConstrained<decimal> !== IConstrained<IComparable>

. IComparable, IConstrained <decimal> IConstparined <IComparable> . , # 4.0 co/contravariance. # 3.0 .

0
source

Read about inconsistency and codimension. Understand that C # generics are invariant, and what you ask for is not what you want.

-1
source

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


All Articles