Alex Rivera | Logout

Referencing a variable from another method

Asked 2012-02-15T20:54:00.740
16

I'm new to C# and I really need to know how to call/use a string from another method.

For example:

public void button1_Click(object sender, EventArgs e)
{ 
    string a = "help";
}

public void button2_Click(object sender, EventArgs e)
{
    //this is where I need to call the string "a" value from button1_click 
    string b = "I need ";
    string c = b + a;          
}

In this example I need to call string "a" defined in function button1_Click() from function button2_Click()

Edit
Report

3 Answers

15

You need to declare string a in the scope of the class, not the method, at the moment it is a "local variable".

Example:

private string a = string.Empty;

public void button1_Click(object sender, EventArgs e) 
{  
    a = "help"; 
} 

public void button2_Click(object sender, EventArgs e) 
{ 
    //this is where I need to call the string "a" value from button1_click  
    string b = "I need"; 
    string c = b + a;           
} 

You can now access the value of your "private field" a from anywhere inside your class which in your example will be a Form.

answered 2012-02-15T20:56:42.013
2
class SomeClass
{
    //Fields (Or Properties)
    string a;

    public void button1_Click(object sender, EventArgs e)
    { 
        a = "help"; //Or however you assign it
    }

    public void button2_Click(object sender, EventArgs e)
    {
        string b = "I need";
        string c = b + (a ?? String.Empty); //'a' should be null checked somehow.
    }
}
answered 2012-02-15T20:58:45.433
1

Make it a class-level variable (global variable), or create a getter and setter for String a, to name a couple options.

answered 2012-02-15T20:55:49.487

Your Answer