Er. Mohammad Jahangeer
Er. Mohammad Jahangeer

Reputation: 969

running Car c=new Driver(); in C#

suppose we've two classes Car and Driver,,
and we are able to make object like

Car c=new Driver();

and able for calling members of Car Class but not of Driver Class Why and When ? ?

Upvotes: 0

Views: 640

Answers (3)

EvilMM
EvilMM

Reputation: 901

In your case, Car is the base class of driver. This is the point why you can create a new driver object but "put" them into a Car object.

But the reason why only the member of the class "car" are visible is, that your object c is from type Car and not from type Driver and Car has less members than Driver.

Upvotes: 0

Timbo
Timbo

Reputation: 28080

Even though the reference c points to a Driver object, the type of the reference (Car) determines which methods can be called on it.

As a side note, having Driver as a class derived from Car does not make much sense. Class inheritance usually can be expressed as a "is-a" relationship, and most drivers are not cars.

Upvotes: 7

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60744

If you are sure that Car is actually a Driver, then you can cast it to a driver to access the members of Driver. So either

((Driver)c).DriverMember();

This will throw an exception if c is not a Driver

Or

Driver d = c as Driver;
if( d != null ){
  d.DriverMethod();
}

The reason is that since c is of type Car, then only Car's members are available.

For example, let's say you have List<Car> where you add some Car objects and some Driver objects. Then it gives perfect sense that only Car's members are possible to use.

Also, I assume that Driver inherit from Car in this case (which is actually a pretty strange inheritance since a driver is not a car).

Upvotes: 0

Related Questions