Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mystery behind System.Array

Tags:

c#

.net

We know System.Array is a abstract class and whatever DataType[] we use runtime creates some concrete implementation for us somehow (vague though).

Consider the following snippet.

int[] someInts = { 1, 2, 3, 4 };
IList<int> collection = someInts;
collection.Clear();

collection.Clear() throws NotSupportedException, Nothing surprising there. When I check to see the "StackTrace" am surprised to see it shows some strange "Type" SZArrayHelper at top of the call stack.

StackTrace:

   at System.SZArrayHelper.Clear[T]()//Note this.. How???
   at TestApplication.Program.Main()

How come that is possible? am calling Clear() method on int[] but then how does the call go to SZArrayHelper.Clear. note that Clear is an instance method in SZArrayHelper defined as below.

private void Clear<T>()
{
    throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}

Who creates the instance of "SZArrayHelper" and also note that Clear method is private. Am very confused about what's happening. If at all an instance of "SZArrayHelper" is created and Clear is called then that helper method doing this call should come in the "StackTrace". But that is not the case here.

Can somebody explain what's happening behind the scenes?

Note:

  1. int[] is just an example, you can pretty much simulate it with any type of array, and not only Clear method Add, Contains etc possesses same behavior.

  2. I tried to debug using reflector addin, which gave me the same results. The debugger shows a direct call to SZArrayHelper.Clear<T>().

  3. Google led me to this .NET Arrays, IList, Generic Algorithms, and what about STL?. That helped to understand the kind of magic that is going on behind the scenes, but some mystery still remains.

like image 318
Sriram Sakthivel Avatar asked Nov 11 '13 19:11

Sriram Sakthivel


1 Answers

You're not seeing any call to that method, because you're invoking it yourself, as weird as that may sound. SZArrayHelper is a CLR wrapper around an array, that implements the IList<T> interface, kinda like the adapter pattern.

From this perspective, it makes sense that collection.Clear invokes SZArrayHelper.Clear directly.

Hans Passant explains this very well here: https://stackoverflow.com/a/11164210/857807

like image 66
dcastro Avatar answered Sep 29 '22 12:09

dcastro