Contravariant delegate value types

Can anyone shed some light on why contravariance does not work with C # value types?

Below does not work

private delegate Asset AssetDelegate(int m); internal string DoMe() { AssetDelegate aw = new AssetDelegate(DelegateMethod); aw(32); return "Class1"; } private static House DelegateMethod(object m) { return null; } 
+7
c # contravariance
source share
2 answers

The problem is that int is not an object .

Object can be marked . The resulting object (aka boxed int) is, of course, an object, but it is no longer int int.

Please note that the β€œ is ” I use above is not the same as the C # is operator. My " - " means "converted to implicit link translation ". This meaning is when we speak of covariance and contravariance.

int is implicit, convertible to an object, but it is not a reference conversion. It should be placed in a box.

An House implicitly converted to Asset through a reference conversion. There is no need to create or modify any objects.

Consider the example below. Both House and Asset variables refer to the same object. On the other hand, the integer and boxedInt keep the same value, but they refer to different things.

 House house = new House(); Asset asset = house; int integer = 42; object boxedInt = integer; 

Boxing and Unboxing is not as simple as it might seem. It has many subtleties and can affect your code in unexpected ways. Mixing boxing with covariance and contravariance is an easy way to make anyone blind.

+5
source share

I agree with Anthony Pegram's comment - it is based on reference types having different memory than value types: the CLR can implicitly use a class of the same type as its super-type class, but when you start using the type value, the CLR will need to bind your integer so that it can work in place of the object.

If you still want it to work, I have a tendency to wrap the declaration in an expression:

 AssetDelegate aw = new AssetDelegate((m) => DelegateMethod(m)); 

I don’t know if this is a good practice or not, as far as the syntax goes, but remember that boxing and unpacking are expensive.

+1
source share

All Articles