0

Lets say I have some data that I want to store and make it available everywhere till the application is closed.

public class Storage(){

public string Aa {set; get;}
public int Bb {set; get;}

}

var insert = new Storage{

Aa = "Im a string",
Bb = 123

};

Now what changes do I need to make insert object available anywhere till the application is closed? In other word, how do I save data in Storage class and make it available till the application is closed?

user7399041
  • 127
  • 1
  • 1
  • 9
  • 1
    Possible duplicate of [Singleton Pattern for C#](http://stackoverflow.com/questions/2667024/singleton-pattern-for-c-sharp) – slawekwin Jan 11 '17 at 07:51

3 Answers3

1

You could give your class a public static property exposing an instance of itself (a singleton pattern). This way, you can access your class properties anywhere:

public class Storage
{
    private Storage() {} 
    private static readonly Lazy<Storage> instance = new Lazy<Storage>(() => new Storage());
    public static Storage Instance { get { return instance.Value; } }

    public string Aa {set; get;}
    public int Bb {set; get;}
}

//access anywhere:
Console.WriteLine(Storage.Instance.Aa);
slawekwin
  • 6,270
  • 1
  • 44
  • 57
0

You have to define the variable insert as a static variable, so that you can access them from everywhere in the application with respect to the class in which the variable is defined. So the definition of the insert variable should be like the following:

public static Storage insert = new Storage(){Aa = "Im a string",Bb = 123};

Let me assume that the variable is defined inside a class called AppVariables the you can access them from any other class like the following:

AppVariables.insert; 
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

You can use static variable so they are accessible from any other class in your project, and they will keep the data as long as the service is running. Try something like:

public class Storage() {
    public static string Aa {set; get;}
    public static int Bb {set; get;}
}

Attention: you may create a single instance of a static class/var! In case you have to keep multiple couples, you better use a static dictionary:

public class Storage() {
    public static Dictionary<string, int> storages {set; get;} 
}
AvrahamL
  • 181
  • 4
  • 16