Verbal Kint
Verbal Kint

Reputation: 425

C# constant property that can only be set once

I continually find myself needing a constant that has to be declared outside of a method's scope but can only be assigned a value inside the method. The result is that I have to null-check the value within the method before I assign a value, but at that point I can't make the constant a constant.

Isn't there a native C# modifier that can handle this? If not, does it exist in similar languages? Why doesn't it exist in C#?

There's a somewhat similar post here: Is there a way of setting a property once only in C#

But it primarily focuses on null-checking with getters and setters

Upvotes: 3

Views: 2448

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

It is not possible to have a class field that can only be set inside a method a method that you specify.

However, you can restrict that for a field that can be only set inside the constructor. The keyword for that in called readonly.

Upvotes: 0

Servy
Servy

Reputation: 203828

When you want to lazily initialize a value use a Lazy instance. This allows you to set the Lazy instance in the constructor, meaning that the field can be readonly, but ensures that the method to create the object isn't called until it's needed, and that it can only ever initialize the value once.

Upvotes: 5

Related Questions