Is it possible to set a object's value, and once that value is set not allow it to change?

I could write a method to do it, but I wasn't sure if there was some sort of modifier I could use?

I need to set a value once, and not allow it to change at all, but the value needs to be dynamic at run-time.

For example, assigning a value to an integer, and as long as that class is alive that has that field, it will always keep that value and if someone, or something, attempts to change the value it throws a fit and/or refuses to change it.

Anyone know if that's possible?

Dani AI

Generated

Short answer: yes. As pointed out, C# gives a few ways to make a field or property write-once at runtime. Which one to use depends on when the value is known (at construction time or later), whether you need to throw on a second write, and whether you must be thread-safe.

A simple, idiomatic approach when the value is known during construction is a readonly field set in the constructor. The compiler prevents further assignment after construction:

class Example
{
    private readonly int _value;
    public Example(int value) { _value = value; }
    public int Value => _value;
}

If the value must be assigned later and you want attempts to change it to throw, implement a one-time setter. The first version below is simple but not thread-safe. The second uses a lock to make the one-time set safe for concurrent callers.

// not thread-safe
private bool _set;
private int _value;
public int Value
{
    get => _value;
    set
    {
        if (_set) throw new InvalidOperationException("Value already set");
        _value = value;
        _set = true;
    }
}

// thread-safe
private readonly object _lock = new object();
private bool _isSet;
private int _val;
public int SafeValue
{
    get { lock (_lock) { return _val; } }
    set
    {
        lock (_lock)
        {
            if (_isSet) throw new InvalidOperationException("Value already set");
            _val = value;
            _isSet = true;
        }
    }
}

Notes and alternatives: const is compile-time only and cannot be used for runtime values. C# 9 introduced init properties for values set only during object initialization — useful for immutable initialization patterns. A readonly field prevents reassigning a reference but does not make the referenced object immutable; use immutable types or defensive copies when you need true immutability. For official details see the C# docs on readonly fields and .

Recommended Answers

All 4 Replies

readonly fields:

readonly fields:

Duh. I feel like an idiot now. I knew that!

Thanks!

Will we bet that I have already felt more like an idiot in my life than you?:D
So don't worry, it is just part of life I guess.

So true...about the part of life comment I mean :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.