Search code examples
c#constructorconstantsfinal

C# variable that can't be changed but need to be initialed in the constructor


I need an attribute that can't be changed after initialisation in the constructor

somthing like this:

private const string banknr;

public ClassName(string banknr)
{
    this.banknr = banknr;
    //from now on "banknr" can't be changed something like a final or const
}

but it just doesn't work, I realy don't understand


Solution

  • That's precisely what the readonly keyword does.

    private readonly string banknr;
    
    public ClassName(string banknr)
    {
        this.banknr = banknr;
        //from now on "banknr" can't be changed something like a final or const
    }
    

    readonly variables can be set in a constructor, but can not be changed.