C #, which cannot be modified, but must be initialized in the constructor

I need an attribute that cannot be changed after initialization 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 really don't understand

+4
source share
3 answers

That is what it does readonly.

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 the constructor, but cannot be changed.

+6
source

If you want the value not to be affected after initialization, you can use the keyword readonly:

public class Class2
{
    public readonly string MyProperty;
    public Class2()
    {
        MyProperty = "value";
    }
}

readonly (C # link):

:

  • .
  • , , , , . , readonly out ref.

, , :

public class Class1
{
    public string MyProperty { get; private set; }

    public Class1()
    {
        MyProperty = "value";
    }
}
+3

readonly const. http://weblogs.asp.net/psteele/63416. : + const: + readonly:

+1

Source: https://habr.com/ru/post/1608853/


All Articles