How to declare a const that can only be initialized at run time

My class contains the constant LOT_SIZE , which cannot be changed. But I can only initialize it at runtime, because I get LOT_SIZE from the securities table at runtime. However, I want to clarify that this is permanent, and I want to protect it from changes from any other places, except for one "friend", where I want to initialize it (table "Securities").

Do we have something for this in C # or do I just need to use LOT_SIZE as a regular variable?

I cannot declare LOT_SIZE as readonly because during the construction of the object the Securities table is not yet read, therefore I do not know the value of LOT_SIZE .

+4
source share
3 answers

The best way is probably to read the value before creating the class that should hold it, so you can pass it to the constructor and put it in the readonly field. But since you ruled it out in an obvious way ...

You can use a read-only property (a property with get but not set) and always access it through the property, except where you originally set the value.

If you don’t even want to risk changing it from your own class, create a class to β€œwrap” the value. This class will do nothing more than read the value if necessary for the first time and set it as a read-only property for your consumer classes.

But no matter what method you choose, do not use the "1970 C macro constant" (ALL_CAPS) for your constant :-)

+3
source

You cannot declare a variable so that it can be modified in one place, and not in any other (except for the fact that you excluded).

I suggest you use some kind of "lazy pattern." Write a class that wraps the value and allows you to set the value exactly once. You can make a variable a reference to an instance of this class read-only.

 class WriteOnce<T> { T _val; bool _isInitialized; public T Value { get { if (!_isInitialized) throw; return _val; } set { if (_isInitialized) throw; _val = value; } } } ... class SomeOtherClass { readonly WriteOnce<int> LOT_SIZE = new WriteOnce<int>(); } 
+1
source

You can make a class to read from your table with a private member variable (even make a Singleton class to get uber fantasy). Then make a static public variable with getter only. This is a bit overkill, but this is the only way to allow it to be installed after initialization, but it can only be changed once.

0
source

All Articles