AJ's blog

July 23, 2006

typeof(Array).GetInterfaces() changes behaviour in .NET 2.0

Filed under: .NET, .NET Framework, C# — ajdotnet @ 12:47 pm

When we migrated an existing project from .NET 1.1 to .NET 2.0 Gerhard (who owns http://www.objectmapper.net/) noted that his mapper suddenly had problems. The cause was an interesting change in the CLR/CTS:

Suppose you were using the interfaces an array exposes like that:

int[]  arrayOfInt = new int[]{1,4,5};

Type[] interfaces = arrayOfInt.GetType().GetInterfaces();

int    i          = interfaces.Length;  // number of supported interfacesobject o          = arrayOfInt;

int    b          = 0;  // counter for implemented interfaces

if (o is ICollection)

    ++b;

if (o is IList)

    ++b;

if (o is IEnumerable)

    ++b;

In .NET 1.1 the resulting value of i was 0. No interfaces supported by arrays, sorry. No, wait! b was 3! So it supports interfaces, but it doesn’t tell!

One may be inclined to call this a bug…. ;-)

Anyway, run the same code in .NET 2.0 and the result of i is 7. The interfaces returned are:

  • {Name = “ICloneable” FullName = “System.ICloneable”}
  • {Name = “IList” FullName = “System.Collections.IList”}
  • {Name = “ICollection” FullName = “System.Collections.ICollection”}
  • {Name = “IEnumerable” FullName = “System.Collections.IEnumerable”}
  • {Name = “IList`1” FullName = “System.Collections.Generic.IList`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]“}
  • {Name = “ICollection`1” FullName = “System.Collections.Generic.ICollection`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]“}
  • {Name = “IEnumerable`1” FullName = “System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]“} 

Noteworthy that it implements the old non-generic collection interfaces as well as the new generic ones.

That’s all for now folks,
AJ.NET

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 244 other followers

%d bloggers like this: