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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With