How to access the derived class properties from base class instance using generic method

742 Views Asked by At

I am trying to access all the properties of my derived class through base class reference variable.

Classes

        public class vehicle
        {
            public int ID { get; set; }
        }

        public class Car : vehicle
        {
            public string type  { get; set; }
            public string Name { get; set; }
        }

Here is the main in Main class

public static void saveCar<T>(T vehicle) where T : vehicle
        {
            //TODO : here I need to access all the propertie values but I dunno how access only derived class values             


        }

I am trying to do this way

static void Main(string[] args)
        {

            Car cr = new Car
            {
                ID = 1,
                type = "car",
                Name = "Maruthi"
            };
            saveCar<Car>(cr);            


        }
2

There are 2 best solutions below

2
On

Why do you have saveCar as a generic method? If the saveCar method is a virtual method on Vehicle you can override and have the required extended save functionality in each derived type. However if you require an external method to handle actions such as save and have Vehicle and its derived classes as simple data representations, you will need to inspect the object and act accordingly. Some like:

    public static void saveCar(Vehicle vehicle)
    {
        if (vehicle != null)
        {
            Console.WriteLine(vehicle.ID);
            if (vehicle is Car)
            {
                var car = vehicle as Car;
                Console.WriteLine(car.Name);
            }
        }
    }
0
On

You can't really ask for T and know your real properties.
I think you should change your design to something like this:

    public abstract class Vehicle
    {
        public int Id { get; set; }

        public virtual void SaveCar()
        {
            // save Id
        }
    }

    public class Car : Vehicle
    {
        public string Type  { get; set; }
        public string Name { get; set; }

        public override void SaveCar()
        {
            base.SaveCar();
            // Save type & name
        }
    }