0 day streak
csharp / beginner
Snippet

Protected State Initialization

Readonly fields protect data from being changed after the object is created. This enhances security and prevents accidental bugs in complex logic.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class SecurityToken
{
// Readonly fields can only be set in the constructor
public readonly string Value;
public SecurityToken(string secret)
{
Value = secret;
}
public void AttemptChange()
{
// Value = "NewSecret"; // This would cause a compiler error!
}
}
Breakdown
1
public readonly string Value;
Declares a field that is immutable once the constructor finishes.
2
Value = secret;
The only place where this field can be assigned a value.