Type.ToString quirk on Array types

There was a recent thread in the MSDN forums where someone was concerned about the behavior of Type.GetElementType. His example was similar to the following:

char [][,][] arr = new char[2][,][];
Console.WriteLine(arr.GetType().GetElementType());

The output he got was:

System.Char[][,]

This puzzled him no end because the element type is clearly char[,][]. He was wondering if this was a bug in GetElementType or even if it was a bug in the C# compiler (incorrectly parsing the array declaration).

Well there is no mystery here. Array types (or rather the runtime type for an array) have a ToString implementation that displays the array using a display format closely resembling the IL syntax for arrays, and not the C# syntax. This is very easily verified with the following code:

Console.WriteLine(typeof(char[][,][,,]));

The output here is:

System.Char[,,][,][]

This is a good idea since the C# array syntax is not universal among CLI languages anyway. Both VB.NET and C++/CLI use array syntax that’s different from this.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s