简体   繁体   中英

Is it best practice for a C# property getter to return a new object?

I am often writing classes that create a new object in a property getter, but I have read this is not necessarily best practice. Eg:

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 anything wrong with that?

See here: Is object creation in getters bad practice? where various upvoted people suggest it is bad practice, eg: "Yes, it is bad practice. Ideally, a getter should not be changing or creating anything". And that reading a property twice should produce identical results (whereas creating a new object will be different each time.)

(I note that in C# the System.Drawing.Rectangle class has a Size property that does return a new object each time.)

Creating a new object is a good defensive strategy to prevent modifications of your object's internals.

However, it should be applied only when the object that you are returning is a mutable, and is not a struct (which should be immutable anyway [why?] ).

CGSize is a struct , so you are creating a new value-typed object here. This is exactly what you should do when you do not store the Size .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM