How do I access a variable declared in one function from a second function?
-
21-06-2021 - |
Pergunta
I'm new to programming in C#, and im looking for a quick solution. I have 2 buttons on form, one is calling the DownloadFileAsync(), and the second one should cancel this operation. Code of first button:
private void button1_Click(object sender, EventArgs e)
{
...
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}
Code of second button:
private void button2_Click(object sender, EventArgs e)
{
webClient.CancelAsync(); // yes, sure, WebClient is not known here.
}
Im looking for an idea how to solve this problem quickly (use the webClient from first function, in block of second).
Solução
That isn't a private variable. webClient
goes out of scope. You will have to make it a member variable of the class.
class SomeClass {
WebClient webClient = new WebClient();
private void button1_Click(object sender, EventArgs e)
{
...
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}
}
Outras dicas
You must to define webClient
globally in your class (scope of variable). webClient
on button2_Click
is out of scope.
Form MSDN: Scopes
The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs.
and
The scope of a member declared by a class-member-declaration is the class-body in which the declaration occurs.
so that
class YourClass
{
// a member declared by a class-member-declaration
WebClient webClient = new WebClient();
private void button1_Click(object sender, EventArgs e)
{
//a local variable
WebClient otherWebClient = new WebClient();
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}
private void button2_Click(object sender, EventArgs e)
{
// here is out of otherWebClient scope
// but scope of webClient not ended
webClient.CancelAsync();
}
}
The webclient is declared in button1_Click method and is avialble in the scope this method
Hence you cannot use it in button2_Click method
Instead the compiler will fail your build
To reslove this please move the webClient declaration outside the method and make it available at class level