2

Let's say I have a class like this:

public class SampleClass
{
    const string UnChangableUserName { get; private set; }
    string Password { get; private set; }

    public SampleClass(string UnChangableUserName, string Password)
    {
        this.Password = Password;
        this.UnChangableUserName = UnChangableUserName;
    }
}

I want the constructor to assign a value to the const, and not for the value to be set when the const is defined. How can I do it?

I'm aware I can simply not use set but using const is more resource efficent and more elegant as well as clearer to other devs to understand, I don't want a set so they will not add it.

0

2 Answers 2

21

You can't. By definition, consts in C# are defined at compile-time, not at runtime. They can't be changed by any code, even constructor code, because they're not even there at runtime - they're replaced by their literal values at every point of usage.

What you're looking for is either readonly fields or read only properties.

  1. Readonly fields are marked by the readonly modifier:

    private readonly string _username;

    Readonly fields are only assignable during construction, either directly assigned in the definition itself (readonly string _username = "blah") or in the constructor. The compiler will enforce this limitation, and will not allow you to set a value anywhere else.

  2. Readonly properties are simply properties that don't expose a setter at all. Until C# 6, you could use them to return the value of a readonly field (as above), but you couldn't assign to them. As of C# 6, though, there's syntax supporting read-only auto-properties that can be assigned: even though there's no explicit setter, there's an implicit setter that can, again, only be called from the constructor, or from a field initializer:

    public string Username { get } = "Username";

    It may look strange that you're setting to a property with no setter, but that's simply an implicit part of the language - there's an implicit backing field that's readonly, and can be set at initialization.

Sign up to request clarification or add additional context in comments.

2 Comments

Readonly properties supported from C# 1... Newer versions bring different syntax to express that so...
Technically, pre-C# 6 properties can be read-only, but not assignable - you can't have assignable read-only auto-properties. You can have properties with getters that return a read-only field, that's true, but you'll have to do the assignment separately.
1

a const is a CONSTANT at compilation. You need a readonly property.

https://stackoverflow.com/a/3917886/910741

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.