1

I had defined two variables reference to structs: ref var x = ref struct_var. they were not equal at first, just like the result of the print out. When I set them to be the same using x=y, they seem to point to the same object generally. But after I modified their member values, they are not synchronized. Did I overlook any grammatical features?

  struct d { public int x, y; };

  static void Main(string[] args)
  { 
    var arr = new[] { new d() { x = 1, y = 2 }, new d() { x = 3, y = 4 } };
    ref var x = ref arr[0];
    ref var y = ref arr[1];
    
    print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // false, false

    x = y; // it seem they ref to the same struct.
    print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // true, true

    x.x = ~y.y; // x.x is not equal to y.x
    print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // false, false

    y.x = x.x; // 
    print(x.GetHashCode() == y.GetHashCode(), object.Equals(x, y)); // true, true
  }
uscq
  • 86
  • 7

1 Answers1

3

x = y doesn't do a reference assignment, it copies the values. You need to use

x = ref y;

Which gives the results you expect:

struct d { public int x, y; }
  
static void Main(string[] args)
{ 
  var arr = new[] { new d{ x = 1, y = 2 }, new d{ x = 3, y = 4 } };
  ref var x = ref arr[0];
  ref var y = ref arr[1];
    
  (x.Equals(y)).Dump(); // False

  x = ref y;
  (x.Equals(y)).Dump(); // True

  x.x = ~y.y; 
  (x.Equals(y)).Dump(); // True

  y.x = x.x; // 
  (x.Equals(y)).Dump(); // True
}

arr now contains (1, 2), (-5, 4).

Luaan
  • 62,244
  • 7
  • 97
  • 116