1

I wonder what gets returned using the get property for C# on an object, is it a reference or it is a copy of what that property is assigned to?

From my understanding it's actually returning a copy instead of a reference. For the code below, I need the 4th line to make Position work (Position is a property of a base class)

    Vector2 position = Position;
    position.x = Mathf.Clamp(Position.x, 0, mScreenSize.x);
    position.y = Mathf.Clamp(Position.y, 0, mScreenSize.y);
    Position = position; //This line is required to clamp the position into Position
Joe
  • 841
  • 2
  • 10
  • 25
  • 4
    It depends on the object. `Vector2` is a struct, so it will be returned by value (a copy). Other classes (objects) are reference types and will be returned by reference. – Ron Beyer Apr 11 '18 at 03:56
  • 2
    See [this](https://stackoverflow.com/questions/9251608/are-structs-pass-by-value). Properties are no different. – ProgrammingLlama Apr 11 '18 at 04:21

1 Answers1

1

It depends on the type you are returning. Properties are no different from other mechanisims.

If it is a value type, then it's a copy, if it is a reference type, then it's a reference.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156