How can I get which class was passed to the method

I have a class with 9 different properties, each of which is a class

public class Vehicles { Car car; //class Train train; //class Plane plane; //class } 

I pass this Vehicle object to the method

eg

 var Vehicles = new Vehicles(); Vehicles.Car = new Car() Object1.WorkOutTransport(vehicle) 

what I need to do in Object1 is a workout for which a "vehicle" was created without using the switch statement and checking if the rest are zero or not.

this is NOT a β€œhomework question” ... I simplified it to illustrate only the problem

a virtual vehicle class has 9 possible classes that can be created

+4
source share
4 answers

I would recommend rethinking your design.

Why not all types of your vehicle implement the common IVehicle interface, then your Vehicles class has one property called Vehicle .

You will have only one property to worry about.

 public Interface IVehicle { ... //Properties Common to all vehicles } public class Car : IVehicle { ... //Properties to implement IVehicle ... //Properties specific to Car } public class Vehicles { public IVehicle Vehicle { get; set; } } var vehicles = new Vehicles(); vehicles.Vehicle = new Car(); ... //Do whatever else you need to do. 
+4
source

Assuming only one is nonempty, you can do this:

 Vehicle instance = vehicle.Car ?? vehicle.Train ?? vehicle.Plane; 

But if you want to do something useful with your instance , you just have to check typeof(instance) and translate it into the desired class.

You might want to consider only one property:

 public class Vehicles { public Vehicle VehicleInstance {get; set;} } 

And move the functionality so that your WorkOutTransport method can act on the Vehicle instance instead of taking care of which subclass it has. Use virtual or abstract methods in the Vehicle class and override in subclasses.

+1
source

If you use different properties without checking whether it is null or not, this cannot be avoided. I propose a base class with a property that identifies the type or overrides the ToString method.

0
source

You can force interface inheritors to indicate their type:

 enum VehicleType { Passenger, Truck, // Etc... } public Interface IVehicle { VehicleType Type { get; } ... // Properties Common to all vehicles } public sealed class Truck : IVehicle { // ... class stuff. // IVehicle implementation. public VehicleType Type { get { return VehicleType.Truck; } } } 

This will allow you not to look at each class, but to know exactly what type to broadcast.

 IVehicle vehicle = GetVehicle(); switch (vehicle.Type) case (VehicleType.Truck) { // Do whatever you need with an instance. Truck truck = (Truck)vehicle; break; } // ... Etc 

You are any other appoarch except switch .

0
source

All Articles