3

Code example:

 var positions = new List<Position>();

 for (int i = 0; i < 20; i++)
 {
     positions.Add(new Position { Code = "A", Value = i });
     positions.Add(new Position { Code = "A", Value = i });
 }
 var test = positions.GroupBy(p => p, new PositionComparer());

public class Position
{
    public string Code;
    public int Value;
}
public class PositionComparer : IEqualityComparer<Position>
{
    public bool Equals(Position x, Position y)
    {
        return x.Code == y.Code && x.Value == y.Value;
    }
    public int GetHashCode(Position pos)
    {
        unchecked
        {
           int hash = 17;
           hash = hash * 31 + pos.Code.GetHashCode();
           hash = hash * 31 + pos.Value;
           return hash;
         }
     }
 }

I have a breakpoint in GetHashCode (and in Equals).
The breakpoint is not hit during the GroupBy, why not?

Gerard
  • 13,023
  • 14
  • 72
  • 125

1 Answers1

1

From the documentation for GroupBy:

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

Unless you actually do something with test in your code the grouping won't actually be executed and therefore your PositionComparer won't get executed either.

petelids
  • 12,305
  • 3
  • 47
  • 57
  • It is the same as with the Results View in the Watch window in Debug mode. Only when you unfold it, "Expanding the Results View will enumerate the IEnumerable". – Gerard May 16 '17 at 13:01
  • @Gerard I think that when you expand Results View, the breakpoint isn't reached, it is only reached if you pass a collection though a foreach (ex.)... Anyone know if is it a compiler specifc behavior? – Rafael Aug 15 '19 at 19:06