Managing keys for shared collections in .NET
Ensuring unique keys for shared collections in .NET
Dealing with shared collection in application is always a bit tricky. You have to take care of concurrent access if you are accessing from multiple threads.
One more thing which does not look so important as it is not difficult to implement is managing keys for addressing values. Whether it is some environment collection like output cache or session in ASP.NET or some sort of shared dictionary object, one thing is common to access values and that is key.
If you keys are not assigned and managed in runtime, developers usually use constants to access collection items. Constant values are calculated in compile-time, so you cannot change them in run-time. This is good because you it is flexible in terms of updating key/constant value. It only takes change in one place to reflect everywhere where you are using that key.
const string SOME_KEY = "SOME_KEY";
However, this approach has one big downsize. There is no guaranty that this key value will not be used in any other place in code. There might be a cases, especially in large size projects where separate teams are working on same project by developing separate modules. All of these modules can access to same shared collection on application level.
Such case is Output Cache in ASP.NET applications. Even if you handle concurrent access and all other high risk potential issue, there is still human factor which can cause a mess and spent time for debugging and fixing the issue. One of these is for sure key management based on constants.
It might happen that different keys have same value and are accessing same shared collection on application level. In this case it would ideal to calculate unique keys only once in a runtime and use them to access values in a shared collection.
One very efficient way to do it is by using static readonly variables because of two main reasons:
- Static ensures that value will be calculated only once when application starts
- Readonly will provide changes of the variable only in a runtime. Consider it as a runtime calculated constant
The last but mot important thing is to ensure uniqueness of key values. This can be simply done by using System.Guid class which is shipped with .NET framework itself. So nothing fancy or complicated to resolve this problem, using only native .NET classes and concepts.
static readonly string SOME_KEY = System.Guid.NewGuid().ToString();
This way, key uniqueness is maintained by code itself, so no more worries that someone will declare the smae key value for shared application collection and one human factr for possible error is eliminated successfully.
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.