Breakpoint that breaks when data changes in a managed language

10,081

Solution 1

This is not possible in C# or any of the other .NET languages due to CLR limitations. The Visual Studio native code debugger supports data breakpoints (link) for C++ code which do exactly this but this is not supported for managed code. You could try to break on or intercept Add and Remove method calls on the collection as suggested in the other answer to this question.

Solution 2

What about swapping out List<T> for ObservableCollection<T> and listen for the CollectionChanged event? It implements the IList<T> interface so there should be enough overlap in available methods to result in syntax and semantic compatibility.

Solution 3

This is now possible in Visual Studio 2019. See release notes here: https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes

This article goes into some detail using Preview 2. https://devblogs.microsoft.com/visualstudio/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Note that this is for .NET Core only and not the soon-to-be-legacy full fledged Windows only .NET framework.

Solution 4

I'm assuming Visual Studio is IDE.

Set a breakpoint, right click it, select condition, type myList.Count, and choose Has Changed.

Solution 5

Subclass List<t> with your own class, then override Count (or Add/Remove) and add a breakpoint in the method you create.

EDIT: As mentioned in comments, this would require a great deal of effort since the Add and Remove methods aren't virtual; a complete rewrite of the methods would be needed.

Also, subclassing Collection<t> would apparently be a better solution (though I can't discern a reason why since Add/Remove aren't virtual members for Collection<t> either; comments?).

Share:
10,081
Jason Thompson
Author by

Jason Thompson

I like to code

Updated on June 05, 2022

Comments

  • Jason Thompson
    Jason Thompson about 2 years

    I have a class with a list property that seems to lose an element under certain circumstances. I cannot find out when this happens.

    So what I'd like to do is set up a Visual Studio breakpoint that will pause the program the moment this value changes. A conditional breakpoint would not work in this scenario, since I have no idea what is removing this breakpoint.

    To put it another way, I want my program to stop the moment myList.Count evaluates to a new number.

    Any ideas on how to do this?