How to Use Global Variables in C#

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

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();

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 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 Can I Declare A Global Variables Model In BLAZOR?

You can inject your class as a singleton service:

builder.Services.AddSingleton<UserInfoGlobalClass>();

In a service include the class as a ctor paramater.

In a component or page:
@inject UserInfoGlobalClass UserInfoGlobalClass

For this to be dynamic though. You will need to embellish your class with an event to notify pages and components to call StateHasChanged() when the contents are updated. I normally set the properties to private set and expose a method to change them that finally invokes the event to notify listeners.

public class UserInfoGlobalClass
{
public string User_Name { get; private set; } = "JOHN SMITH";
public string User_Email { get; set; } = "JOHNSMITH@gmail.com";
public string User_Role { get; set; } = "Administrator";
public string USER_ID { get; set; } = "85f04683-0d37-4947-a09d-bbb464a92480";

public event EventHandler UserChangedEvent;

public void SetUser(User user)
{
User_Name = user.Name;
... repeat for properties.
UserChangedEvent?.Invoke();
}
}

Use in another service.

builder.Services.AddScoped<SomeOtherService>();
public class SomeOtherService : IDisposable
{

private readonly UserInfoGlobalClass userInfoGlobalClass;

public SomeOtherService(UserInfoGlobalClass userInfoGlobalClass)
{
this.userInfoGlobalClass = userInfoGlobalClass;
userInfoGlobalClass.UserChangedEvent += UserChanged;
}

public void UserChanged(object sender, EventArgs e)
{
// Process user details change.
}

public void SetNewUserMethod()
{
userInfoGlobalClass.SetUser(new User { ... });
}


public void Dispose() => userInfoGlobalClass.UserChangedEvent -= UserChanged;
}

In a page or component:

@implements IDisposable
@inject UserInfoGlobalClass UserInfoGlobalClass

...

@code {
protected override void OnInitialized()
{
userInfoGlobalClass.UserChangedEvent += StateHasChanged;
}

public void public void Dispose() => userInfoGlobalClass.UserChangedEvent -= StateHasChanged;
}


Related Topics



Leave a reply



Submit