Tuesday, October 14, 2008

Adding Methods

Public Methods


public void PressHorn()
{
Console.WriteLine("Toot toot!");
}


To use the new method, change the code within the Main method as follows:

static void Main(string[] args)
{
Vehicle car = new Vehicle();
car.PressHorn(); // Outputs "Toot toot!"
}


Private Methods

To provide for encapsulation, where the internal functionality of the class is hidden, some methods will be defined as private. Methods with a private protection level are completely invisible to external classes. This makes it safe for the code to be modified to change functionality, improve performance, etc. without the need to update classes that use the public interface. To define a method as private, the private keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method is private by default.

The following method of the car class is a part of the internal implementation not the public interface so is defined as being private.

private void MonitorOilTemperature()
{
// Internal oil temperature monitoring code...;
}

To demonstrate that this method is unavailable to external classes, try the following code in the Main method of the program. When you attempt to compile or execute the program, an error occurs indicating that the MonitorOilTemperature method cannot be called due to its protection level.

static void Main(string[] args)
{
Vehicle car = new Vehicle();
car.MonitorOilTemperature();
}

No comments: