My class contains LOT_SIZE constant which can not be changed. But I can initialize it only during execution, because I obtain LOT_SIZE from Securities table at runtime. However I want to make clear that this is constant and I want to protect it from changes from any other places except one “friend” place where I want to initialize it (“Securities” table read).
Do we have something for that in C# or I just have to use LOT_SIZE as regular variable?
I can not declare LOT_SIZE as readonly because during object construction “Securities” table still not read and so I don’t know LOT_SIZE value.
The best way is probably to read the value before creating the class that must hold it, so you can pass it into the constructor and put it into a
readonlyfield. But as you’ve excluded doing it the obvious way…You could use a read-only property (a property with a get but no set) and always access it via the property except in the place where you initially set up the value.
If you don’t even want to risk changing it from within your own class, then create a class to “wrap” the value. This class would do nothing more than read the value when required the first time and expose it as a read-only property to your consumer classes.
But whichever way you choose, please don’t use “1970’s C macro constant” (ALL_CAPS) naming for your constant 🙂