Search code examples
c#classobjectoopinheritance

Converting objects to Subclass


I want to make a class Vehicle and two classes (PassengerVehicle and FreightVehicle) that inherit it. The problem is that when the user enters the type of vehicle he wants and when I convert an object from Vehicle to the desired type, I can't use those class methods later. Here is my code, how can I fix this?

using System;

namespace Vehicle_Primer
{
    enum FuelType
    {
        Gas,
        Diesel
    }

    class Vehicle
    {
        private FuelType FuelType { get; set; }
    }

    class PassengerVehicle : Vehicle
    {
        private int SeatNumber { get; set; }
        private int PassengerNumber { get; set; }

        public void CheckSeats()
        {
            if (PassengerNumber > SeatNumber) Console.WriteLine("Not enough seats");
            else Console.WriteLine("Enough seats");
        }
    }

    class FreightVehicle : Vehicle
    {
        private int Capacity { get; set; }
        private int Mass { get; set; }

        public void CheckCapacity()
        {
            if (Mass > Capacity) Console.WriteLine("Load capacity exceeded");
            else Console.WriteLine("Load capacity not exceeded");
        }
    }

    internal class Program
    {
        static void Main()
        {
            Vehicle vehicle = null;
            while (true)
            {
                Console.WriteLine("Enter vehicle type");
                string input = Console.ReadLine();
                if (input == "passenger")
                {
                    vehicle = new PassengerVehicle();
                    break;
                }
                else if (input == "freight")
                {
                    vehicle = new FreightVehicle();
                    break;
                }
                Console.WriteLine("Wrong input");
            }

            if (vehicle is FreightVehicle)
            {
                vehicle.CheckCapacity();
            }
            else
            {
                vehicle.CheckSeats();
            }
        }
    }
}

Solution

  • I think the problem here is you are not using properly pattern matching. When using pattern matching you need to declare a variable to test against, like as follow:

            if (vehicle is FreightVehicle freight)
            {
                freight.CheckCapacity();
            }
            else if (vehicle is PassengerVehicle passenger)
            {
                passenger.CheckSeats();
            }
    

    In other words, when using pattern matching, it implicitly forces you to declare the variable to test, and if the type is correct you can use that object and its methods and properties.

    For a more detailed expalanation, you can see this link at Type Tests.