Write a C#.Net program to define a class Person having members – name and address. Create a subclass called Employee with members – staff_id and salary. Create ‘n’ objects of the Employee class and display all the details of the Employee.

Answer:

using System;

namespace EmployeeDetails
{
    // Base class Person
    class Person
    {
        public string Name;
        public string Address;

        public Person(string name, string address)
        {
            Name = name;
            Address = address;
        }
    }

    // Subclass Employee inheriting from Person
    class Employee : Person
    {
        public int StaffId;
        public double Salary;

        public Employee(string name, string address, int staffId, double salary)
            : base(name, address) // Calling the constructor of the Person class
        {
            StaffId = staffId;
            Salary = salary;
        }

        // Method to display employee details
        public void DisplayDetails()
        {
            Console.WriteLine("\nEmployee Details:");
            Console.WriteLine("Name: " + Name);
            Console.WriteLine("Address: " + Address);
            Console.WriteLine("Staff ID: " + StaffId);
            Console.WriteLine("Salary:" + Salary);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Accept number of Employee objects to be created
            Console.Write("Enter the number of employees: ");
            int n = int.Parse(Console.ReadLine());

            // Array to store Employee objects
            Employee[] employees = new Employee[n];

            // Accept details for each employee and create Employee objects
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine("\nEnter details for Employee" + (i + 1) + ":");

                Console.Write("Name: ");
                string name = Console.ReadLine();

                Console.Write("Address: ");
                string address = Console.ReadLine();

                Console.Write("Staff ID: ");
                int staffId = int.Parse(Console.ReadLine());

                Console.Write("Salary: ");
                double salary = double.Parse(Console.ReadLine());

                // Create Employee object and store in the array
                employees[i] = new Employee(name, address, staffId, salary);
            }

            // Display details of all employees
            Console.WriteLine("\nDisplaying Employee Details:");
            for (int i = 0; i < n; i++)
            {
                employees[i].DisplayDetails();
            }
            Console.ReadLine();
        }
    }
}
Scroll to Top