Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Visual Studio debugger properly evaluate expressions that involve generic type arguments?

In the following code:

        private static void Main(string[] args)
        {            
            var listy = new List<DateTime> { DateTime.Now };
            MyMethod(listy);
        }

        static void MyMethod<T>(List<T> myList)
        {
            // put breakpoint here
        }

If I break in the debugger, open QuickWatch on "myList", I see:

myList
   [0]
   Raw View

If I select the "[0]" node and click Add Watch, the expression that is added to Watch:

(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>(myList)).Items[0]

This expression seems correct, and yet, the watch window shows the following error:

The best overloaded method match for 'System.Collections.Generic.Mscorlib_CollectionDebugView.Mscorlib_CollectionDebugView(System.Collections.Generic.ICollection)' has some invalid arguments

This seems like a bug in the debugger. Why does this happen? And is it documented anywhere?

like image 796
Omer Raviv Avatar asked Aug 17 '11 18:08

Omer Raviv


1 Answers

This looks like a bug in the C#'s expression evaluator's overload resolution logic. The combination of invoking a generic type constructor and passing a bound generic seems to be a key. Removing either of these seems to fix the problem. For example you can invoke the expression mentioned by explicitly casting myList to ICollection<DateTime> (this doesn't fix all cases I tried though)

Here's a sample program I wrote to narrow down the problem

class C<T> {
    public C(ICollection<T> collection) {

    }
}

static void Example<T>(ICollection<T> collection) {
}

At the same break you can try the following evaluations

  • Example(myList) - Works without error
  • new C<DateTime>(myList) - Fails with the same error

At this point i think you should file a bug on Connect. It's definitely a bug (similar code works fine in VB.Net)

like image 97
JaredPar Avatar answered Oct 27 '22 17:10

JaredPar