Is it possible to have fields that are assigned only once?

I need a field that can be assigned, wherever I want, but it can be assigned only once (therefore, subsequent assignments should be ignored). How can i do this?

+6
c # readonly
source share
4 answers

Then it will not be readonly field. Your only options for initializing real readonly fields are the field initializer and constructor.

However, you can implement some kind of readonly functionality using properties. Make your field as a property. Implement the instance freeze method, which flipped a flag that states that it is no longer allowed to update only readable parts. Ask installers to check this flag.

Keep in mind that you refuse to check compile time to check runtime. The compiler will tell you if you are trying to assign a value for the readonly field from anywhere except the declaration / constructor. Using the code below you will get an exception (or you can ignore the update, none of which is optimal IMO).

EDIT: to avoid repeating validation, you can encapsulate the readonly function in the class.

The revised implementation might look something like this:

class ReadOnlyField<T> { public T Value { get { return _Value; } set { if (Frozen) throw new InvalidOperationException(); _Value = value; } } private T _Value; private bool Frozen; public void Freeze() { Frozen = true; } } class Foo { public readonly ReadOnlyField<int> FakeReadOnly = new ReadOnlyField<int>(); // forward to allow freeze of multiple fields public void Freeze() { FakeReadOnly.Freeze(); } } 

Then your code might do something like

  var f = new Foo(); f.FakeReadOnly.Value = 42; f.Freeze(); f.FakeReadOnly.Value = 1337; 

The last statement throws an exception.

+17
source share

Try the following:

 class MyClass{ private int num1; public int Num1 { get { return num1; } } public MyClass() { num1=10; } } 
+1
source share

Or maybe you mean a field that everyone can read, but only the class itself can write? In this case, use a private field with a public recipient and a private installer.

 private TYPE field; public TYPE Field { get { return field; } private set { field = value; } } 

or use the automatic property:

 public TYPE Field { get; private set; } 
0
source share

in Java and possibly in any other languages ​​(please correct me if I am wrong), you can do this by declaring a variable / field STATIC (can be accessed anywhere as long as it is open) and FINAL (value may not change at run time after assignment). :)

0
source share

All Articles