Is it best practice for the recipient of C # properties to return a new object?

I often write classes that create a new object in getter, but I read that this is not necessarily the best practice. For instance:

public class Board
{
    public float Width { get; }
    public float Height { get; }
    public CGSize Size { get { return new CGSize(this.Width, this.Height); } }

    public Board(float width, float height)
    {
        this.Width = width;
        this.Height = height;
    }
}

Is there something wrong with this?

See here: Is object creation in bad getter practice? , where various people in high demand argue that this is bad practice, for example: "Yes, this is bad practice. The getter should not change or create anything." And that reading a property twice should give identical results (whereas creating a new object will be different every time.)

(In C #, the System.Drawing.Rectangle class has a Size property that returns every new object every time.)

+4
1

- .

, struct ( [why?]).

CGSize - struct, . , , Size.

+3

Source: https://habr.com/ru/post/1693152/


All Articles