Reputation: 131
So I have 4 classes: Employee (base class), PartTime : Employee, FullTime : Employee, Manager : Employee. I'm trying to access unique but can't figure out exactly how. I tried casting but that didn't work. Here's what I have so far.
Employee emp1 = new Manager();
emp1.FirstName = txtFirst.Text;
emp1.LastName = txtLast.Text;
emp1.Ssn = Convert.ToInt32(txtSSN.Text);
emp1.HireDate = Convert.ToInt32(txtHire.Text);
emp1.TaxRate = Convert.ToDecimal(txtTax.Text);
emp1.Email = txtEmail.Text;
emp1.PhoneNum = Convert.ToInt32(txtPhone);
if (emp1 is PartTime)
{
emp1.HourlyRate = txtRate.Text;
emp1.HoursWorked = txtHrs.Text;
}
if (emp1 is FullTime)
{
emp1.Salary = Convert.ToDecimal(txtSalary.Text);
emp1.VacationDays = Convert.ToDouble(txtVacation.Text);
emp1.SickDays = Convert.ToDouble(txtSick.Text);
emp1.IsTaxExempt = comboTax.SelectedIndex == 0 ? true : false;
emp1.HasInsurance = comboInsurance.SelectedIndex == 0 ? true : false;
}
if (emp1 is Manager)
{
(Manager)emp1.BonusEarned = Convert.ToDecimal(txtBonus.Text);
(Manager)emp1.Department = comboDepartment.SelectedText;
(Manager)emp1.OfficeLocation = txtOffice.Text;
}
In this example, Manager has the properties BonusEarned, Department, and OfficeLocation but Employee, FullTime, and PartTime don't.
Upvotes: 0
Views: 69
Reputation: 48134
Ugh, I think that is just invalid syntax. You're doing cast in the LHS of an assignment statement... It doesn't work like that. Cast has to be on the RHS so the result can be assigned. Instead try something like this;
if (emp1 is Manager)
{
var man = (Manager)emp1
man.BonusEarned = Convert.ToDecimal(txtBonus.Text);
man.Department = comboDepartment.SelectedText;
man.OfficeLocation = txtOffice.Text;
}
Upvotes: 1
Reputation: 25361
Try this (pay attention to the parenthesis):
((Manager)emp1).BonusEarned = Convert.ToDecimal(txtBonus.Text);
((Manager)emp1).Department = comboDepartment.SelectedText;
((Manager)emp1).OfficeLocation = txtOffice.Text;
Upvotes: 2