I’m trying to do a little bit of work with my classes and wondering whether what I want to do is possible:

I have my base class `Car`.
Public Class Car
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine
}
public void Drive()
{
///does stuff
}
}
I have another class that inherits from Car, called Mercedes.
Public Class Mercedes : Car
{
private readonly IExhaust _exhaust
public Car(IExhaust exhaust, IEngine engine) : base(engine)
{
_exhaust = exhaust
}
public override void Drive()
{
///does stuff with _exhaust
}
}

I use these classes in a situation where the object Car is defined and used.
My current code tries to switch to use the drive method of Mercedes whilst maintaining the information given to the Car object:
var car = New Car(//dependencies met)
car.AVaribale = "It's filled";
var merc = car as Mercedes;
merc.Drive();
The usage above leads to a null object reference for the dependencies of Mercedes – IExhaust. Is there a way to do the above? Or am I approaching this incorrectly?
You are. You’re creating an instance of Car and trying to downcast it to Mercedes. You can’t. It should be an instance of Mercedes, which you can assign to a variable of type Car.
Actually, although some may disagree, I recommend declaring classes either sealed or abstract. Then the code will make more sense.
Shouldn’t merc be null at this point? A Mercedes is a Car, but a Car is not a Mercedes, so you could do.
But not the other way around.
The key here is where you write new Car().
This creates a Car object, which is not a Mercedes object, and never will be. Once you create an object, you can’t change its type.
What you can do is use variables of different types to reference that object, but only if the object already inherits from (or implements) that type. So this is ok:
But this is not: Car car = new Car(); // The car variable can point at a car, or a mercedes Mercedes merc = (Mercedes)car; // This gives an exception because the car is not a mercedes
For the last line, you wrote car as Mercedes, which is the same as what I wrote except that if the car isn’t a Mercedes, what you wrote will give you Null (and probably give exceptions later on in the code), whereas what I wrote gives you an exception straight away.
C# devs
null reference exceptions

source