Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand your question correctly, it sounds like you just want to set a field's value once (the first time), and not allow it to be set after that. If that is so, then all the previous posts about using Lazy (and related) may be useful. But if you don't want to use those suggestions, perhaps you can do something like this:</p> <pre><code>public class SetOnce&lt;T&gt; { private T mySetOnceField; private bool isSet; // used to determine if the value for // this SetOnce object has already been set. public bool IsSet { get { return isSet; } } // return true if this is the initial set, // return false if this is after the initial set. // alternatively, you could make it be a void method // which would throw an exception upon any invocation after the first. public bool SetValue(T value) { // or you can make thread-safe with a lock.. if (IsSet) { return false; // or throw exception. } else { mySetOnceField = value; return isSet = true; } } public T GetValue() { // returns default value of T if not set. // Or, check if not IsSet, throw exception. return mySetOnceField; } } // end SetOnce public class MyClass { private SetOnce&lt;int&gt; myReadonlyField = new SetOnce&lt;int&gt;(); public void DoSomething(int number) { // say this is where u want to FIRST set ur 'field'... // u could check if it's been set before by it's return value (or catching the exception). if (myReadOnlyField.SetValue(number)) { // we just now initialized it for the first time... // u could use the value: int myNumber = myReadOnlyField.GetValue(); } else { // field has already been set before... } } // end DoSomething } // end MyClass </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload