Home > Mobile >  Get properties from object
Get properties from object

Time:01-25

I have a method that must run different ways, depending on the type of the object received. But, I dont know how to acces the properties of the object.

I'm also not shure that it is the corret way to create the derivated 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 acces the properties of the car?
                //does not contain a definition for 'Plate'
                Console.WriteLine(thing.Plate);
            }

            if (thing is Bike)
            {
                //how do I acces 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 shure 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.

CodePudding user response:

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());
     }
}
  • Related