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 do开发者_运维问答cumented anywhere?
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 errornew 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)
Looks that way. I've been able to replicate the error. Mscorlib_CollectionDebugView<T>
has only one constructor accepting ICollection<T>
and List<T>
implements ICollection<T>
. Also, explicitly casting to ICollection<T>
works:
(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>((ICollection<DateTime>)myList)).Items[0]
精彩评论