2

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
  }
4
  • stackoverflow.com/questions/46036142/… ? Commented Jan 21, 2021 at 6:45
  • No, x/y is a ref struct type, I can NOT put ref keyword to x = y. I am working on vs 2017. Commented Jan 21, 2021 at 7:04
  • 1
    In VS 2017, you need <LangVersion>7.3</LangVersion> in the project file to enable the feature. Commented Jan 21, 2021 at 7:06
  • @user202729, After I read answer twice, it did hit my head, Good Answer. Thanks you all guys. Commented Jan 21, 2021 at 7:47

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.