king yau king yau - 4 months ago 18
ASP.NET (C#) Question

How to create a global variable in C#?

I need to use a global variable in my .net project. However, i cannot handle it between two methods..

my code:

string str;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
str = "i am a string";
showString();
}
}

void showString()
{
aspLabel.Text = str; //error
}


Question update:

I will not consider to use
showString(str)
because this variable is used many methods.. For example, I have a click event which need to use it.

protected void Btn_Click(object sender, EventArgs e)
{
exportToExcel(str);
}


Therefore, I need to create it in global!

Answer

The answer is don't do global variables (you also can't).

Closest to Global is having it in a class that is static and as a static member - but I really think it would be the wrong approach for most of the cases. Static classes/members usually make code more coupled and reduces testability so pick carefully when you decide to do so.

Do instead: (pass parameter)

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    string str = "i am a string";
    showString(str);
  }
}

void showString(string str)
{
  aspLabel.Text = str;
}

Or:

public class SomeClass
{
    private string str;

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        str = "i am a string";
        showString();
      }
    }

    protected void Btn_Click(object sender, EventArgs e)
    {
       exportToExcel(str);
    }

    void showString()
    {
      aspLabel.Text = str;
    }
}

Here you can change the str to be a property or a different access modifier as you wish, but this is the general idea.

If you have it as public instead of private you will be able to access it from different classes that hold an instance to this class. like this:

public class SomeClass
{
    public string Str { get; private set; }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        Str = "i am a string";
        showString();
      }
    }

    protected void Btn_Click(object sender, EventArgs e)
    {
       exportToExcel(Str);
    }

    void showString()
    {
      aspLabel.Text = Str;
    }
}

public class SomeOtherClass
{
    public SomeOtherClass()
    {
        SomeClass someClass = new SomeClass();
        var otherStr = someClass.Str;
    }
}