Enforced immutability: Difference between revisions
Content added Content deleted
(Added Dyalect programming language) |
(Added C#) |
||
Line 164: | Line 164: | ||
};</lang> |
};</lang> |
||
=={{header|C sharp}}== |
|||
Fields can be made read-only (a runtime constant) with the '''readonly''' keyword. |
|||
<lang csharp>readonly DateTime now = DateTime.Now;</lang> |
|||
When used on reference types, it just means the reference cannot be reassigned. It does not make the object itself immutable.<br/> |
|||
Primitive types can be declared as a compile-time constant with the '''const''' keyword. |
|||
<lang csharp>const int Max = 100;</lang> |
|||
Parameters can be made readonly by preceding them with the '''in''' keyword. Again, when used on reference types, it just means the reference cannot be reassigned. |
|||
<lang csharp>public void Method(in int x) { |
|||
x = 5; //Compile error |
|||
}</lang> |
|||
Local variables of primitive types can be declared as a compile-time constant with the '''const''' keyword. |
|||
<lang csharp>public void Method() { |
|||
const double sqrt5 = 2.236; |
|||
... |
|||
}</lang> |
|||
To make a type immutable, the programmer must write it in such a way that mutation is not possible. One important way to this is to use readonly properties. By not providing a setter, the property can only be assigned within the constructor. |
|||
<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 Point(int x, int y) => (X, Y) = (x, y); |
|||
public int X { get; } |
|||
public int Y { get; } |
|||
}</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |