Reputation: 35
I have a method that is supposed to accept a structure variable and return a bool. This is working fine - at least in terms of syntax, perhaps.
private bool equalsidcomparison(Employee newGuy)
{
foreach (Employee E in employees)
{ if (E.Name == newGuy.Name || E.phone == newGuy.phone) { return true; } return false; }
return false;
}
Later on in a button click method, where i am passing data to a struct variable's fields(newGuy), and then passing newGuy to the method above, I am told that newGuy is an unassigned local variable.
Employee newGuy;
newGuy.id = nextIDnumber;
newGuy.Name = txtbName.Text;
newGuy.department = (string)comboDept.SelectedItem;
newGuy.title = comboJob.SelectedText;
newGuy.phone = txtbPhone.Text;
foreach (Employee E in employees)
{
if (equalsidcomparison(newGuy) == true) { };
}
I feel like this is an easy fix but i'm new and at a loss for what it should be. I've looked around to no avail and I can't stray too far from the process i've used, as it's part of an assignment.
Upvotes: 1
Views: 49
Reputation: 156
You need to instantiate an instance of your variable -- like so:
Employee newGuy = new Employee();
newGuy.id = nextIDnumber;
...
You could also write it as 'var newGuy = new Employee();' (depending on who you ask, this is the better syntax...)
You could also create your object like: (note -- this requires your 'set' method to be accessible)
Employee newGuy = new Employee()
{
id = nextIDnumber,
Name = "something",
...
};
I would also recommend using consistent casing in your variable names. (id, Name, title, ...). In general, the standard for c# is to use PascalCase for publicly available methods/properties.
Upvotes: 0
Reputation: 726699
You need to initialize newGuy
with operator new
. You can combine its field initialization with the declaration:
Employee newGuy = new Employee {
id = nextIDnumber
, Name = txtbName.Text
, department = (string)comboDept.SelectedItem
, title = comboJob.SelectedText
, phone = txtbPhone.Text
};
Upvotes: 2