It’s Beta For a Reason!

Today, I was in the process of creating a branch of Elevate to support .NET 4.0 when I came across a subtle, but breaking change in the Enumerable.Count function. The following code works in .NET 3.5, but fails in .NET 4.0 Beta 2:

[TestClass]
public class CountBug
{
    public class MyIList : IList<int>
    {
        public MyIList()
        {
            GetEnumeratorWasCalled = false;
            CountWasCalled = false;
        }
        
        //...non-relavent IList members excluded for this post...
        
        public bool GetEnumeratorWasCalled { get; set; }
 
        public IEnumerator<int> GetEnumerator()
        {
            GetEnumeratorWasCalled = true;
            return null;
        }
 
        public bool CountWasCalled { get; set; }
 
        public int Count
        {
            get
            {
                CountWasCalled = true;
                return 0;
            }
        }
    }

    [TestMethod]
    public void CountBehavior()
    {
        var list = new MyIList();

        Assert.AreEqual(0, list.Count());
        Assert.IsTrue(list.CountWasCalled);
        Assert.IsFalse(list.GetEnumeratorWasCalled);
    }
}

The Enumerable.Count method in .NET 4.0 Beta 2 fails to recognize that MyIList implements ICollection<T>, so instead of returning the .Count property, it calls the MyIList’s GetEnumerator() method and walks every item in the list to determine the count. In .NET 3.5, MyIList is identified as an ICollection<T> implementer and the .Count property is correctly used.

It’s also worth noting that it does not seem to be possible to create a MSTest test project in Visual Studio 2010 Beta 2 that targets .NET 3.5. It will silently upgrade any of your .NET 3.5 test projects to .NET 4.0 even if you select 3.5 as the target framework when creating a project!

I’ve filed the following bugs on connect, so hopefully they get resolved soon!

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=514122

[update: I initially posted a link to the wrong bug. The above link has been corrected.]

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=514130

This entry was posted in C#, Elevate, Framework Bugs, Visual Studio. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>