In a different question on stackoverflow somebody suggested to write an extension method for an array, but used the this IList<T> interface in the extension method. I commented it should be an array but he declined. I tested it, and of course, he’s right… 🙂
Extension method:
public static void Fill<T>(this IList<T> array, T value)
{
for(var i = 0; i < array.Count; i++)
{
array[i] = value;
}
}
Test code:
[Test]
public void Stackoverflow()
{
int[] arr = new int[] { 1,2,3,4};
arr.Fill(2);
Assert.AreEqual(2, arr[0]);
Assert.AreEqual(2, arr[1]);
Assert.AreEqual(2, arr[2]);
Assert.AreEqual(2, arr[3]);
}
An array is not an IList<T>. Why does this even compile? Let alone, pass?!
From section 12.1.2 of the C# 4 specification:
It’s worth noting that if you create a rectangular array or a one-dimensional array which has a lower bound other than zero, those do not implement
IList<T>.In the CLI, there are actually two terms: vector and array. A vector is a one-dimensional collection with a lower bound of zero, and is optimized to heck and back by the JIT. An array can have multiple dimensions and different lower bounds, and isn’t subject to as thorough optimization.
A
T[]in C# is always a vector. You can’t cast an object which is a CLI-array toT[]– you end up with an exception like this: