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:
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.
I tried to debug using reflector addin, which gave me the same results. The debugger shows a direct call to SZArrayHelper.Clear<T>()
.
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…