I have some dictionary objects which doesn't change during application life time. I am planning to use static readonly variables, could anyone provide inputs on below points.
Difference between initializing directly as static readonly properties and static properties with GET operator backed up with private readonly static variables.
Is there any risk using them as I have read online not to use public static variables. Does this apply for this situation.
I have some dictionary objects which doesn't change during application life time.
When you mark a variable of Dictionary type readonly, you prevent the replacement of the dictionary that you assign with another dictionary. You do not make that dictionary read-only, in the sense that as soon as a caller gets his hands on that dictionary, he is free to change in any way that he wants, wiping it clean, or setting incorrect values (by mistake, no doubt). If you need to make a Dictionary read-only, consider borrowing an implementation of a read-only wrapper from this answer.
In general, the only advantage of adding a property on top of a variable, or having a {get;private set;} automatic property, over a readonly static is your ability to perform additional checks in the setter, or adding some code in the getter (say, to collect access statistics or for logging). There are also implications to accessing the field through reflection. It does not look like you are doing any of that, so exposing a readonly variable sounds appropriate and does not present additional risks.
EDIT: (on using reflection) When you access object data through reflection, you must specify if you are accessing a property Xyz or a field Xyz. In contrast, when you write a C# program, you write SomeClass.Xyz, and the compiler figures out if it's a property or a field for you. If you create a class that exposes a field Xyz, and later decide to replace it with a property Xyz, recompiling the code that refers to Xyz directly is all it takes. However, if you wrote some code that accesses Xyz by through the reflection API, that code would need to be rewritten, because the compiler would not be able to catch the change for you.
Since, as fields, they cannot be changed after the static constructor has run, there is no reason in terms of immutability and thread safety in having static readonly properties wrapping them.
Note, however, that properties over fields are sometimes needed - data binding is one example, as is the use of reflection (where it may be easier if you standardize on one or the other).
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