-4

In Windows application development using C# .NET, how do you make a global variable or global instance of a class, which can then be directly used by all other windows forms, e.g. form1, form2, etc.

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
Yogesh
  • 13
  • 6

4 Answers4

2

You can create a static class and define a static variable inside it.

All the classes in your project can refer to it using MyGlobalVariables.GlobalVariable

public static class MyGlobalVariables
{
   public static int GlobalVariable;
}
Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69
1

Create a public static class which holds the global variables

eg.

public static class GlobalValues
{
      public static int UserId{get;set;}
}

Read more about C# Global Variable

Also I guess you should read about Classes and Structs

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
0

Make it as a static variable and static class, e.g.

private static string foo = "this is static";

public static class Bar {}

SteveC
  • 15,808
  • 23
  • 102
  • 173
Peri
  • 11
  • 2
0

Create singleton class so that instace can be created once and used across application

public class Global 
{
    private static readonly Global instance = new Global();
    public static Global Instance
    {
        get
        {
            return instance;
        }
    }

    Global()
    {
    }
    public string myproperty
    {
        get;set;
    }
    }

Usage: Global.Instance.myproperty

dotnetmirror.com
  • 293
  • 2
  • 10