Is there a difference between a "base" and a "w650" when referring to a field, property, or method of a parent object?

Consider the following code:

public class Vehicle { public void StartEngine() { // Code here. } } public class CityBus : Vehicle { public void MoveToLocation(Location location) { ////base.StartEngine(); this.StartEngine(); // Do other stuff to drive the bus to the new location. } } 

Is there any difference between this.StartEngine(); and base.StartEngine(); , except that in the second case, the StartEngine method cannot be transferred or overridden in the CityBus class? Is there a performance impact?

+6
optimization syntax c # oop
source share
3 answers

The only difference is the explicit call to look at your parent class compared to the implicit one, which gets to the same place with simple inheritance. The difference in performance is negligible. as Hans Passant said, calling base.StartEngine () will cause strange behavior if you first make StartEngine virtual.

You do not need any qualifier to get the right place. this.StartEngine() almost always redundant when explicitly encoded. You may have code that indirectly places the this link in the list of objects, but then it refers to the called list:

 public class Vehicle { public void StartEngine() { // Code here. } //For demo only; a method like this should probably be static or external to the class public void GentlemenStartYourEngines(List<Vehicle> otherVehicles) { otherVehicles.Add(this); foreach(Vehicle v in Vehicles) v.StartEngine(); } } 
+3
source share

It makes no difference, StartEngine () is not virtual. You should not use the database if you have ever reorganized it to make it virtual. Prospective differentiation is not measurable.

+6
source share

In this case, there is no difference in performance.

Since StartEngine is not virtual, the compiler, and then the jitter, knows exactly what is meant by calling it, whether in the database, in the derived class, or outside the class.

If StartEngine was virtual, and the compiler and / or jitter could deduce that you are calling against CityBus and not something received from CityBus, then what (very small) difference is there can also be removed as optimization.

If StartEngine was virtual, and the compiler and / or jitter could not determine whether you are calling the CityBus against the derived class, then the distinction between a base or direct call is vital for correctness.

As a rule, the only place where you can call the base method with base. , is in the redefinition of this method to make it more understandable. If the distinction between a base and a derived version is important elsewhere, you should try reorganizing so that base.SomeVirtualMethod() base.SomeNonVirtual() in base.SomeNonVirtual() , which is therefore always available, even if derived.SomeVirtualMethod() changes the behavior.

+2
source share

All Articles