Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Base class constructor arguments

Tags:

c#

I learning C#. I want to see what is the best way to implement inheritance. I have a Employee base class and a PartTime derived class. Employee class only receives First and Last name and has a method to print full name.

I want to know what is the proper way to pass First and last name so that when I just call PartTime class I should be also able to print full name from the calling program. At the moment it is showing blank as full name:

class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee("John", "Doe");
        // emp.PrintFullName();

        PartTime pt = new PartTime();

        float pay=pt.CalcPay(10, 8);
        pt.PrintFullName();  

        Console.WriteLine("Pay {0}", pay);
        Console.ReadKey();
    }
}

public class Employee
{
    string _firstName;
    string _last_name;

    public Employee(string FName, string LName)
    {
        _firstName = FName;
        _last_name = LName;
    }

    public Employee() { } 

    public void PrintFullName()
    {
        Console.WriteLine("Full Name {0} {1} ", _firstName, _last_name);
    }
}

public class PartTime : Employee
{
    public float CalcPay(int hours, int rate)
    {
        return hours * rate;
    }
}
like image 273
user2719435 Avatar asked Jan 26 '26 06:01

user2719435


2 Answers

You can call the base class constructor from you derived class like this:

public class PartTime : Employee
{
    public PartTime(string FName, string Lname)
         : base(FName, LName)
    { }
}

and then create it,

PartTime pt = new PartTime("Part", "Time");
like image 139
JLe Avatar answered Jan 27 '26 20:01

JLe


Try this:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    //method implementations removed for clarity

}

public class PartTime:Employee
{
    public PartTime(string firstName, string lastName)
        : base(firstName, lastName)
    {

    }
}

Note that your base constructor will run before any code in your derived constructor, should you need further initialization logic in the PartTime class.

like image 24
joelmdev Avatar answered Jan 27 '26 19:01

joelmdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!