Calling base in a class allows us to access the method, constructor, or property of the inherited class.
From a previous article we learned that when using Virtual and Override, when calling the method Visual Studio will look for the method in the descendant class first and then move on to the parent class if it isn't found. This can cause an issue, though, because if the parent class method never executes we will lose any functionality we might need. Let's take a look at a concrete example of this.
We have a virtual method in the Employee class called TakeBreak that reduces the Employee's HoursWorked by the time they've taken on their break that has overrides in other classes. Having this be virtual means that if the descendant class doesn't have an override this method will execute, but if they do the override will execute.
So let's look at the overrides for the Attendant and Boss classes. The Attendant sits on the booth whereas the Boss goes home for lunch. They both do something different when their TakeBreak methods are called.
We have a problem, though. The Attendant never gets time taken out of their Timesheet. We don't care about the Boss (they can do whatever they want), but the Attendant needs to have their time recorded or they'll get sacked for time theft. The solution to this is to call the Employee class's (parent/inherited class) TakeBreak method using base.
Now Visual Studio will find the TakeBreak method in the Attendant class and then calling the base class's TakeBreak method tells the application that we also want to execute the method in the Employee class. In a sequence diagram this looks like:
Now when an Attendant object's TakeBreak method is called it does two calls and we get the functionality of the inherited Employee class.
Let's look at this method in the Attendant class.
We are getting an error that there is no 'food' item for them to steal. So is there a method we can use to get a Food object? Sure, but it's in the Employee class.
The mistake not to make is to call base. and then the method in the parent class.
While this "works", Visual Studio gives a warning basically saying "you don't need to call base you have direct access to it."
When we change it to this. the warning will go away. This is because the FindFoodItem is really just a member of the current instance of the current class.
Where this becomes increasingly important is when differentiating between an override and a virtual. Say we make FindFoodItem virtual and override it in the Attendant class.
Then in the StealItem method we need to be very particular of whether we want to use the FindFoodItem method in the Attendant class (this) or this FindFoodItem method in the parent class (base).