Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 339
Koen Van Looveren Avatar asked Sep 24 '15 16:09

Koen Van Looveren


3 Answers

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.

like image 193
Carlos Rodriguez Avatar answered Oct 17 '22 22:10

Carlos Rodriguez


If you want value can't be touched after initialization you can use readonly keyword:

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

readonly (C# Reference):

You can assign a value to a readonly field only in the following contexts:

  • When the variable is initialized in the declaration.
  • For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.

If you want the value can't be touched out of your class you can use a private setter in a property:

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

    public Class1()
    {
        MyProperty = "value";
    }
}
like image 23
Reza Aghaei Avatar answered Oct 17 '22 22:10

Reza Aghaei


You want readonly instead of const. The difference can be found at http://weblogs.asp.net/psteele/63416. Summary here:

  • const: only initialized at declaration
  • readonly: can be initialized at declaration or constructor
like image 1
Harvey Pham Avatar answered Oct 18 '22 00:10

Harvey Pham