Monday, August 17, 2009

Another C# Fluke

Here's some code:
var l = new List<int?>();
l.Add( null );
( ( System.Collections.IList)l ).Add( null );

You would expect those two Adds to be equivalent and that after executing them l.Count would be equal to 2.

Instead you get an ArgumentException on the second Add. Turns out System.Collections.Generic.List implements both Add(...) and System.Collections.IList.Add(...) and the interface specific one does some input validation not done by the other Add. This validation doesn't understand Nullable types, so you get an exception.

I guess its a probably a bug, due to the fact that Nullable<> behaves kind of strangely through reflection.

No comments:

Post a Comment