Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
If i have :
C#
class Car{
// any fields here.
}
 
class BMW : Car{
// any fields here.
}
 
void main(){
BMW myBMW = new BMW(); // Case 1 -> it works
Car myBMW = new BMW(); // Case 2 -> it works
}


my question is Case 1 = Case 2 ? and what's difference and advantages. and which one is better ?
Posted
Updated 15-Feb-15 8:16am
v4
Comments
Thomas Daniels 15-Feb-15 14:02pm    
BMW myBMW = new Car(); does not compile.
[no name] 15-Feb-15 14:09pm    
oh reverse i mean Car myBMW = new BMW();

so whats difference
Tomas Takac 15-Feb-15 14:21pm    
You should use BMW myBMW = new BMW(); - there is no point or benefit in storing it as Car. But your example it very limited. What are you going to do with the instance?
[no name] 15-Feb-15 14:28pm    
well its derived class question my man, so i just want to know what case i should use ? initialize derived instance only as it was, or initialize it via base class ?

1 solution

You can access any object using a reference of it's ancerstor's (parent or above) type. Of course in this case you have access only to the fields defined at that level. That's the difference.

BMW myBMW = new BMW();
You can access all field defined in Object, Car and BMW.

Car myCar = new BMW();
You can access only field defined in Object and Car. Still myCar is a renference to a BMW type object. Thus casting it back to BMW is valid.
 
Share this answer
 
v2
Comments
[no name] 15-Feb-15 14:29pm    
YAS ZORGO u always give good answers :D

that's what i need, but when should i use case 2 ? Car myCar=new BMW(); please explain when should i use it
Zoltán Zörgő 15-Feb-15 14:35pm    
Think of GUI. All buttons, dropboxes, input fields, and so on are all controls. A form has only a list of controls, but you add those different objects to the controls list. To be able to do that, all those need to be descendants of control. If you create your special type of button, it will probably be a descendant of button. But it will still be a descendant of control too, thus could be added to the form's control list. The control defines common things like position, size, and of course click event. If you click on a form, the framework will walk trough the control list, and check which of them is affected by that click. And will cascade the event to that one. At that level it is indifferent which kind of control it is - it can be one predefined in the framework, but could be a special one made by you.

In general there is no need for Car myCar=new BMW() styled constructions. But indirectly such a list is made of such references.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900