I have in my program a struct type called Square which is used to represent the location (int Rank, int File) of a square on a chess board.
If I assign Square by new Square sq(); say and then I want to reassign it, is it better to do so by
sq = new Square(rank, file);
or by writing an internal Set method and calling Set thus
sq.Set(rank, file);
What I am asking is when you use new on a struct, does the runtime reallocate new memory and call the constructor or does it reuse the existing memory? If it does the former then it would be better to write a Set method to avoid overheads would it not? Cheers.
The traditional thinking these days is the value types should be immutable, so you would not want to have a
Setmethod unless that is returning a newSquareobject and not mutating the original. As such,And
Should ultimately perform the same operation.
But given this approach,
GenerateSquarewould also possibly be better as a static method ofSquarerather than something depending upon any given instance. (An instance method would be more useful if something about the existing instance was used in the creation of a new instance.)