Enforced immutability: Difference between revisions
Content added Content deleted
(add FreeBASIC) |
m (C# added the case for readonly members of structs) |
||
Line 147: | Line 147: | ||
<lang csharp>public string Key { get; }</lang> |
<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. |
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> |
<lang csharp>public readonly struct Point |
||
⚫ | |||
{ |
{ |
||
public Point(int x, int y) => (X, Y) = (x, y); |
public Point(int x, int y) => (X, Y) = (x, y); |
||
Line 154: | Line 153: | ||
public int X { get; } |
public int X { get; } |
||
public int Y { 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> |
}</lang> |
||