I want to print the salary of invoked (any of them) child class in the inherited method of Detail()
. this cannot be done in this scenario. How would I get the salary with all other details of an employee.
Here is the code
using System;
class Employee
{
public int ID;
public string Name;
public string Gender;
public string City;
public void Detail()
{
Console.WriteLine("Name: {0} \nGender: {1} \nCity: {2} \nID: {3}", Name, Gender, City, ID); //I want to get Yearly or Hourly Salary with these all
}
}
class PermanatEmp : Employee
{
public float YearlySalary;
}
class TempEmp : Employee
{
public float HourlySalary;
}
class Class4
{
static void Main()
{
PermanatEmp pe = new PermanatEmp();
pe.ID = 101;
pe.Name = "XYZ";
pe.Gender = "Male";
pe.City = "London";
pe.YearlySalary = 20000;
pe.Detail(); // how to get Salary with these all
}
}
You can't and shouldn't - there's no guarantee that an Employee
will have a salary.
Instead, any class which does have a salary can override ToString
to include all the properties it wants to. I'd suggest overriding ToString
instead of having a Detail
method that just prints the information out, by the way.
(As a side note, I would strongly advise you not to use public writable fields. Use properties instead.)
See more on this question at Stackoverflow