Elvin
Elvin

Reputation: 367

Why is it not possible to set a Public Var?

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?

Upvotes: 3

Views: 18216

Answers (4)

ppeterka
ppeterka

Reputation: 20726

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:

Upvotes: 2

tukaef
tukaef

Reputation: 9214

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.

Upvotes: 5

Habib
Habib

Reputation: 223247

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

Upvotes: 2

Tigran
Tigran

Reputation: 62246

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.

Upvotes: 6

Related Questions