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
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.
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";
}
}
You want readonly instead of const. The difference can be found at http://weblogs.asp.net/psteele/63416. Summary here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With