BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Creating a Simple Class in C#

The second article in the C# Object-Oriented Programming tutorial describes how classes are created in C# and how behaviour, in the form of publicly visible and private, hidden methods can be added. This demonstrates some of the uses of encapsulation.

Adding Methods

Public Methods

Public methods are part of the class's public interface, ie. these are the methods that can be called by other objects. If you have not created methods before, you should review the following articles from the C# Fundamentals tutorial:

The syntax for creating methods described in the above articles must be modified slightly to make the methods visible to external objects. To achieve this, the public keyword is used as a prefix. The following code added to the vehicle class provides a new method for pressing a vehicle's horn. Make sure that you add the code within the class's code block.

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();
}

Limitations

This article has described the creation of a basic class with public and private methods. However, every object that is generated from this class is identical, as it currently has no state. In the next article in the series, we will add properties to the class to resolve this.

22 September 2007