3

I am trying to set the following public var:

var collection = new Dictionary<string, Statistics>();

I want to be able to use the same collection all through my application and i therefore want to create it right at the top when the applications starts.

How would i do this?

Elvin
  • 367
  • 3
  • 5
  • 16
  • Sorry i was not clear enough. I want all of my Form1.cs to access it, not different .cs files :) – Elvin Nov 30 '12 at 07:47
  • 4
    `var` can only be used for local variables. Just use the type name `Dictionary` in its place. – Mike Zboray Nov 30 '12 at 07:48
  • @Elvin: I suggest you edit your question then, as "all through my application" definitely has a different connotation. – Jon Skeet Nov 30 '12 at 07:50
  • @Elvin Would I have seen your explanatory comment earlier, I wouldn't have made efforts to provide valuable answer to a totally and entirely different question. Please correct your question, and next time use more accurate wording. – ppeterka Nov 30 '12 at 08:57

4 Answers4

6

There is no concept of a global variable in C#. You always have to declare variable inside some class/scope.

What you can do, is to make it accessible via public modifier, like a property (say).

Just an idea:

public class Shared
{
     public Dictionary<string, Statistics> CollectionDic {get;set;}

     public Shared() {
        CollectionDic  = new Dictionary<string, Statistics>();
     }
}

After you can access it like:

var shared = new Shared(); 
shared.CollectionDic.Add(..)
...

You have to workout by yourself, what fits your exact needs.

Tigran
  • 61,654
  • 8
  • 86
  • 123
5

You can create it as a public static field or property in public class (optionally also static):

public class Variables
{
    public static Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();
}

Then access it in code:

Variables.collection.Add(...);

Note that it is not thread-safe approach. So if you intend to use static dictionary in multithreading app, it's better to either have static methods, wraping the dictionary in thread-safe way (as Jon Skeet mentioned) or use thread-safe collections, for exapmle ConcurrentDictionary.

tukaef
  • 9,074
  • 4
  • 29
  • 45
  • 2
    ... although it's worth noting that static members are usually thread-safe, and `Dictionary<,>` simply isn't. It would be better to have static methods for the required operations, wrapping the dictionary in a thread-safe way. It would be better still to avoid the statics in the first place of course... – Jon Skeet Nov 30 '12 at 07:49
2

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:

Community
  • 1
  • 1
ppeterka
  • 20,583
  • 6
  • 63
  • 78
  • @downvoter: come on, give a reason for the downvote to give the opp to enhance/correct the answer! –  Nov 30 '12 at 07:48
  • @JonSkeet I will get a massive amount of donwvotes, but I have to ask: is it a worse idea than to have it get implemented in a hackish/non-standard way, that will require man-hours to figure out why and what is going on? – ppeterka Nov 30 '12 at 07:55
  • 1
    I'm a closet upvoter here - In a largish project, I would rather see a singleton (or preferably, an IoC container managed instance) being injected via interface rather than have tightly coupled statics destroy the unit testability of the code. To be honest, in most circles I work in, the term "Singleton" now has a looser connotation than the GoF pattern and refers to any mechanism for the coupling and lifetime management of a single instance (e.g. look up `Singleton Orchestrations` in BizTalk). – StuartLC Nov 30 '12 at 08:03
  • 1
    @ppeterka: I wasn't suggesting that it should be done in a hackish way. I'm suggesting that a singleton *is* a hackish way, compared with using an IoC container to inject dependencies appropriately. Basically, singletons are global state, with all the normal attendant problems. Note that your singleton implementation is poor, too - it's not thread-safe. See http://csharpindepth.com/Articles/General/Singleton.aspx – Jon Skeet Nov 30 '12 at 08:15
  • @JonSkeet from that aspect, it is a totally valid argument, using IoC and dependency injection is a lot better solution by all means. As for the code, I pasted it from the MSDN link - which is _supposed_ to be _the_ reference regarding C# information - but [in fact, there is a better source of information](http://meta.stackexchange.com/questions/9134/jon-skeet-facts) As for the thread safety issue, I'll edit the answer accordingly – ppeterka Nov 30 '12 at 08:20
2

The error you are getting is:

The contextual keyword 'var' may only appear within a local variable declaration

I believe you are trying to define your collection as:

public partial class Form1 : Form
{
    var collection = new Dictionary<string, Statistics>();

You can't use var keyword at this level,

I want all of my Form1.cs to access it, not different .cs files

You may define it like:

Dictionary<string, Statistics> collection = new Dictionary<string, Statistics>();

It will be available to all the methods inside the Form1 class

Habib
  • 219,104
  • 29
  • 407
  • 436