Reputation:
Learning C# and hit a snag.
Why isn't the variable 'number' used here?
public partial class Form1 : Form
{
static string labelText = "";
static string number = "";
public Form1()
{
InitializeComponent();
}
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
I keep getting a warning that field 'number' is assigned but not used.
Upvotes: 0
Views: 138
Reputation: 13
It happens because of the string
in the instruction string number = this.serialNumber.Text;
, which is declaring a new variable, different from the class field, despite having the same name. Remove the string
modifier and the instruction will refer to the class field already declared.
Upvotes: 0
Reputation: 2709
Change these lines:
static string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
to
private string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
number = this.serialNumber.Text;
}
Upvotes: 1
Reputation: 11035
First off, the warning is valid, and relates to the static
member, which, in fact, is assigned and never used. The one in serialNumber_TextChanged
is local to that method and by definition, different.
This: "Why isn't the variable 'number' used here?"...I do not understand.
Upvotes: 0
Reputation: 10968
In your serialNumber_TextChanged
method you declare a local variable called number
. So if that is your complete code you never actually assign anything to Form1.number
apart of the static initialization.
Upvotes: 1
Reputation: 44201
string number
declares a new local variable which hides the static member variable.
Upvotes: 2
Reputation: 57272
That's exactly what's happening: you are assigning a value to the variable number
, and then you don't do anything with that variable.
Upvotes: 0
Reputation: 8902
string number = this.serialNumber.Text;
this line creates a new string.
try this to avoid the warning
public partial class Form1 : Form {
static string labelText = ""; static string number = ""; public Form1() { InitializeComponent(); } private void serialNumber_TextChanged(object sender, EventArgs e) { number = this.serialNumber.Text; }
Upvotes: 3