Global Variables in C#.Net

How to declare a variable for global use

Avoid global variables and static keyword at all unless you 100% sure there is no other address your solution (sometimes you might be forced to use statics typically with legacy code hot fixes).

  1. Statics/globals make tight code coupling
  2. Breaks OOD principles (Typically Dependency Injection, Single Responsibility principles)
  3. Not so straightforward type initialization process as many think
  4. Sometimes makes not possible to cover code by unit test or break ATRIP principles for good tests (Isolated principle)

So suggestion:

  1. Understand Problem in the first place, roots, what are you going to achieve
  2. Review your design

Global variables in c#.net

Use a public static class and access it from anywhere.

public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}

used like so, from master page or anywhere:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();

You don't need to make an instance of the class; in fact you can't because it's static. new Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because const is implicitly static by nature.

The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)

You can make as many static classes as you like and name them whatever you want.


Sometimes programmers like to group their constants by using nested static classes. For example,

public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}

and access them like so:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;

How to set a global variable inside c# method

I don't think you can define global variables, but you can have static members.

public static class MyStaticValues
{
public static string currentUrl{get;set;}
}

And then you can retrieve that from anywhere in the code:

String SiteName = MyStaticValues.currentUrl + value.ToString();

In .NET, is there a concept of global variables?

In VB.NET, you can add module file. In that module file, you had to declare variable and/or functions with Public. But this is only in VB.NET

Example, module file would be like this

Module UserDetails

Public SqlCon as SqlConnection
Public DataSet as DataSet
Public dataAdaptr as SqlDataAdapter

End Module

In above example, i am using sql connection, data set, data adapter from any form, class and module.

This example is being used in my projects already. You can use this in your Asp.net projects too.

Global variables in Visual C#

How about this

public static class Globals {
public static int GlobalInt { get; set; }
}

Just be aware this isn't thread safe. Access like Globals.GlobalInt

This is probably another discussion, but in general globals aren't really needed in traditional OO development. I would take a step back and look at why you think you need a global variable. There might be a better design.

how to store in a global variable c#

If we are talking about a Windows Forms application, and by "global" you mean "common across the process," then you can use a static variable.

In this example i create a special class just to hold static variables, and declare one field and one property that will be available to your program and will hold one and only one value across the entire process.

static class GlobalVariables
{
static public string SomeVariable { get; set ; } //As a property
static public string SomeOtherVariable; //As a field
}

Note that if your program is multi-threaded, it may be a good idea to put a critical section around static variables, like this:

static class GlobalVariables
{
static private string LockObject = new Object();
static private string _someVariable;

static public string SomeVariable
{
get
{
lock(LockObject) { return _someVariable; }
}
set
{
lock(LockObject) { _someVariable = value; }
}
}
}

How to use Global Variables in C#

On each post back, the instance of Page(Books) is re-created, so you will not get the value of Book_CategoryName after button click.
An approch is to store the variable in ViewState.

private const string KEY_Book_CategoryName = "Book_CategoryName";
public String Book_CategoryName
{
get
{
return ViewState[KEY_Book_CategoryName] as string;
}
set
{
ViewState[KEY_Book_CategoryName] = value;
}
}

The other approch can be store the value in a hidden field of the page. The idea is to store the value somewhere that can persistent during post back.

How to create a global variable in ASP.NET Core Web API application?

somewhere in project

public static class Config{
public static Dictionary<string,string> Application = new Dictionary<string,string>();
}

elsewhere

Config.Application["froop"] = "noodle";

of course you will have to deal with race conditions, etc



Related Topics



Leave a reply



Submit