'In Unity, while debugging, If I watch "System.Text.RegularExpressions.GroupCollection".Item[String], it gives an error

I'm using Regular Expression in Unity.(Unity2020.3 with Visual2019)

As shown in the picutre below.
I can use groups[str] to get the group.
But while debugging, watching it will raise an error.

image



Solution 1:[1]

I just looked into this and I first though: well this may be the result of some side effect that the debugger tries to avoid. However in other cases the debugger happily evaluates expressions with side effects.

So I checked the relevant code and found something strange. This is the implementation of the two indexers:

public Group this[int groupnum] => GetGroup(groupnum);
public Group this[string groupname]
{
    get
    {
        if (_match._regex == null)
        {
            return Group._emptygroup;
        }
        return GetGroup(_match._regex.GroupNumberFromName(groupname));
    }
}

Since the evaluation leads to "one or more errors occurred" I thought the issue must be either in the GetGroup method, or in the GroupNumberFromName method. Nowever evaluating groups[1] does return the group just fine.

So it has to be GroupNumberFromName, right?

Well, I also evaluated rx.GroupNumberFromName("TheGroup") and it returns 1 as it should without any issues.

So I evaluated groups[rx.GroupNumberFromName("TheGroup")] and it also works. This is almost literally the same thing that the string parameter indexer itself does internally. However for some reason the debugger has issues evaluating the expression.

So I would assume some strange behaviour / bug in the debugger / code analyser which causes this behaviour. Maybe someone who actually works on the debugger could shed some light here, though I don't think we get much more information on that issue. It seems to be a mysterious limitation of the debugger. A bug report wouldn't hurt I guess.

Personally I always try to avoid too complex expressions in the watch window, especially those which could have side effects.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bunny83