简体   繁体   中英

Should a C# struct have only read-only properties

I was reading though a question about impure methods on StackOverflow here and it got me thinking about struct design best practise.

Reading an example about creating an immutable struct here properties are defined as with getters only.

public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public bool HasValue { get { return hasValue; } }

Other examples elsewhere including in System.Drawing.Point the properties have getters and setters.

public int Y {
    get {
        return y;
    }
    set {
        y = value;
    }
}

The design guidelines don't specify but they are quite terse. What would be the recommended approach for struct properties? Readonly or allow writing?

The design guidelines are pretty clear on this:

X DO NOT define mutable value types.

Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

As for System.Drawing.Point , there are other factors (like performance) that were important enough to break this design guideline. See Why are System.Drawing Rectangle, Point, Size etc mutable structs and not classes?

Structures should generally either try to behave as immutable objects or as a bunch of variables stuck together with duct tape (eg the coordinates of a point). These are two disjoint usage patterns, and MSDN guidelines are suitable for the first but not the second.

All properties of the former kind of structure should be read-only; the latter kind of structure should expose all of its state via public fields, but may perfectly reasonably also provide "convenience" properties which are computed in defined fashion based upon the contents of public fields. For example, a Rectangle may have fields X , Y , Width , and Height , and convenience properties Right and Bottom . Such properties wouldn't expose functionality that isn't already directly accessible via the public fields, but would allow some usage patterns to be implemented more conveniently.

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