EDIT
The comments of the OP showed, that the requirement is only to be able to access the variable through the one .cs code. Please disregard the following, and please vote delete if you think that this answer is not a valuable addition to the question for future visitors of this topic. Or vote up, if you think it has enough added value to stay.
What I meant for the original question, regarding I want to be able to use the same collection all through my application
In an object oriented environment, if this is a requirement that can not be surpassed by refactoring/restructuring the application, you should definitely use the Singleton design pattern
A singleton is a pattern, which guarantees that only one instance of the given class exists (per application contex/virtual machine, of course), and that that instance can be accessed from everywhere in the context of the same application.
That is:
- create a class (e.g. by name MyDictionary)
- implement the necessary functions you want from it (you want this to be independent of the underlying implementation)
- make it a singleton by following the article
- decide if you need lazy loading
- I'd recommend to always use thread safe implementation when dealing with singletons to avoid unwanted consequences.
- access from whenever you like
Example: (from the C#Indepth link, second version, having simple thread safety, take note who the author of the article is!)
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
BEWARE always take thread safety into count!
As I got a response from @JonSkeet (yikes!), I think I have to explain the rationale behind my answer:
Pros:
- It is better than having some non-standard way of doing so
- It is better than having to pass it around to every bit of code that exists
Cons:
- It is absolutely not recommended, if this requirement can be circumvented by any means
- having a singleton map around is a serious bad smell: keeps references throughout the life of the application, leading to massive leaks more often than not
- multithreaded behaviour is something that is not trivial, and especially difficult to go after if something misbehaves only very rarely (hidden race conditions, and whatever else lurking under the bed of a programmer during nightmares)
Also recommended reading: