Search code examples
c#classtypesderived-class

Get properties from object


I have a method that must run different ways, depending on the type of the object received. But, I don't know how to access the properties of the object.

I'm also not sure that it is the correct way to create the derived classes. I have the following code:

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Car mustang = new Car();
            mustang.Color = "Red";
            
            Method(mustang);
        }
        
        public static void Method(Vehicle thing)
        {   
            if (thing is Car)
            {
                // how do I access the properties of the car?
                // does not contain a definition for 'Plate'
                Console.WriteLine(thing.Plate);
            }

            if (thing is Bike)
            {
                // how do I access the properties of the bike?
                // does not contain a definition for 'HasRingBell'
                Console.WriteLine(thing.HasRingBell.ToString());
            }
        }
    }

    public class Car : Vehicle
    {
        public string Color { get; set; }
        public string Plate { get; set; }
    }

    public class Bike : Vehicle
    {
        public string Color { get; set; }
        public bool HasRingBell { get; set; }
    }

    public class Vehicle
    {
        public bool HasWheels { get; set; }
        public bool RunsOnGas { get; set; }
    }
}

I'm not sure what are the correct terms to search for it.

I'm expecting to be able to access the properties of the original object, the Car, or Bike.

I imagine the method could receive in a generic way a Car or Bike (a Vehicle).

Then I can check its type, and go on from there.


Solution

  • You're close, you just need to create the local variable -

    public static void Method(Vehicle thing)
    {
         if (thing is Car carThing)
         {
             Console.WriteLine(carThing.Plate);
         }
    
         if (thing is Bike bikeThing)
         {
              Console.WriteLine(bikeThing.HasRingBell.ToString());
         }
    }