Ability to use value types

Consider a static function TranslateAllCoords:

static class CoordinateTransformation
{
  public static void TranslateAllCoords(ref int x, ref int y, ref int z, 
                                        int amount)
  {
    x+=amount;
    y+=amount;
    z+=amount;
  }
}

Then, later in the code, you:

int x=0, y=0, z=0;
...
CoordinateTransformation.TranslateAllCoords(ref x, ref y, ref z, 5);
...

But by calling TranslateAllCoords, you are actually changing the types of values ​​(i.e., whole chords) and usually the types of values ​​should be immutable. Are there any rules that are violated here, or is this a completely correct construct that goes around the “value types must be immutable” construct, changing only the built-in value types?

+5
source share
2 answers

Values ​​are immutable. Variables that contain value types are mutable. Variables change, so they are called "variables."

, , , .

struct Point { public int X; public int Y; public int Z; }
...
Point p = new Point();
p.X = 123;

, , " p". . p , - . p, , . .

:

struct Point { public int X { get; private set; } ... etc }

!

Point p = new Point(123, 456, 789);
p = new Point(100, 200, 300);

, , , .

:

static Point Translate(Point p, int offset) 
{
    return new Point(p.X + offset, p.Y + offset, p.Z + offset);
}
...
Point p = new Point(100, 200, 300);
p = Translate(p, 5);

., , p , , .

+17

. .

+1

All Articles