Enforced immutability: Difference between revisions
m
C# added the case for readonly members of structs
(add FreeBASIC) |
m (C# added the case for readonly members of structs) |
||
Line 147:
<lang csharp>public string Key { get; }</lang>
On value types (which usually should be immutable from a design perspective), immutability can be enforced by applying the '''readonly''' modifier on the type. It will fail to compile if it contains any members that are not read-only.
<lang csharp>public readonly struct Point
public readonly struct Point▼
{
public Point(int x, int y) => (X, Y) = (x, y);
Line 154 ⟶ 153:
public int X { get; }
public int Y { get; }
}</lang>
On a struct that is not made readonly, individual methods or properties can be made readonly by applying the '''readonly''' modifier on that member.
<lang csharp>public struct Vector
{
}</lang>
|