Aaron
Aaron

Reputation: 1

C#: How can I use reflection in order to cast an object?

public static void myMethod(Object myObject)
{

}

My object is of type SportCar. How can I create a new Object (Something like this)

SportCart sportCar = myObject as SportCar

Later Edit: I don't know what is the type of myObject. It could be SimpleCar, AbcCar etc

Upvotes: 0

Views: 135

Answers (3)

Massif
Massif

Reputation: 4433

Do the car classes have a common type, and you just want to cast to that i.e.:

BaseCar baseCar = myObject as BaseCar;

Or are you trying to examine the type first and then cast to the correct type, i.e.:

if(myObject is SimpleCar)
{
  var simpleCar = myObject as SimpleCar;
}

If you're thinking of doing the second, I strongly recommend you use the first. And if you're using the first you don't need to worry about what type of car it is.

Upvotes: 0

Jackson Pope
Jackson Pope

Reputation: 14660

It sounds like you want one of two things. Either have a base class Car or interface ICar that has all the shared behaviour that cars have and then you can do:

ICar car = myObjectAsCar;
car.Drive(Speed.VeryFast);

Or, you want to do different things, depending on what type of car it is:

if (SportCar sporty = myObject as SportCar)
{
     sporty.Drive(Speed.VeryFast);
}
if (HybridCar hybrid = myObject as HybridCar)
{
     hybrid.Drive(Speed.Economical);
}

Upvotes: 1

Jamiec
Jamiec

Reputation: 136249

This is generally where you would use an interface. In your case, myMethod must be doing something specific with the argument passed in. Lets take a simple example; say myMethod was responsible for starting the car, you would define an interface such as

public interface ICar
{
    void Start()
}

Then the argument to myMethod would be of type ICar rather than object.

public void myMethod(ICar car)
{
   car.Start();
}

Now mymethod does not need to know (or care!!) what ICar is presented, be it AbcCar, SportsCar etc. as long as that class implements ICar

public class SportsCar : ICar
{
   public void Start() 
   {
      Console.WriteLine("Vroom Vroom. SportsCar has started");
   }
}

public class AbcCar : ICar
{
   public void Start() 
   {
      Console.WriteLine("Chug Chug. AbcCar has started");
   }
}

Upvotes: 4

Related Questions