C# variable

Hello all i am beginner in C# i have more than 10 buttons on a form i want to use a global variable in this form how can i do this?:slight_smile:

you start by defining the variable with “public” keyword, then you can call the variable within events on the form :slight_smile:

A Global variable:

private string _test;

public string Test
            return _test;
            _test = value;

To access it in the form, it would be: “this.Test”. Outside the form, if the class name was: “TestMe”, it would be:

TestMe letsdoit = new TestMe();

letsdoit.Test = "Whats up world";

//To access it would be:

Textbox1.Text = letsdoit.Test;

//Which would print: Whats up World.

Hope it helps.

I need to know how to include a global variable in C# for a window based application, so that it is in all the forms?

The code I used above would work as a Global variable in both Win Forms and Web Forms if you use basic OOP principles. Just as long as the class is public.

C# has no global variable. The alternative is what USPatriot mentioned above which is actually creating a public property

a “global” variable in c# would be a static variable.

public static class functions()
public static string text = “test”;


I’d also note that in most cases you don’t want globals.