Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
314 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...