This is a mirror of official site: http://jasper-net.blogspot.com/

Subterranean IL: Generics and array covariance

| Sunday, November 14, 2010
Arrays in .NET are curious beasts. They are the only built-in collection types in the CLR, and SZ-arrays (single dimension, zero-indexed) have their own commands and IL syntax. One of their stranger properties is they have a kind of built-in covariance long before generic variance was added in .NET 4. However, this causes a subtle but important problem with generics. First of all, we need to briefly recap on array covariance.

SZ-array covariance

To demonstrate, I'll tweak the classes I introduced in my previous posts:

public class IncrementableClass {
   public int Value;
   
   public virtual void Increment(int incrementBy) {
       Value += incrementBy;
   }
}

public class IncrementableClassx2 : IncrementableClass {
   public override void Increment(int incrementBy) {
       base.Increment(incrementBy);
       base.Increment(incrementBy);
   }
}

In the CLR, SZ-arrays of reference types are implicitly convertible to arrays of the element's supertypes, all the way up to object (note that this does not apply to value types). That is, an instance of IncrementableClassx2[] can be used wherever a IncrementableClass[] or object[] is required. When an SZ-array could be used in this fashion, a run-time type check is performed when you try to insert an object into the array to make sure you're not trying to insert an instance of IncrementableClass into an IncrementableClassx2[].

Read more: Simple-talk

Posted via email from .NET Info

0 comments: