 .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.
What is a Class?
The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract all of the characteristics and behaviour of a type of object. Once instantiated, an object is generated that has all of the methods, properties and other behaviour defined within the class.
A class should not be confused with an object. The class is the abstract concept for an object that is created at design-time by the programmer. The objects based upon the class are the concrete instances of the class that occur at run-time. For example, the Car class will define that all cars have a make, model and colour. Only at run-time will an object be instantiated as a Red Ferrari Dino.
Creating a Class
The basic syntax for the creation of a new class is very simple. The keyword 'class' followed by the name of the new class is simply added to the program. This is then followed by a code block surrounded by brace characters {} to which the class' code will be added.
class class-name {}
To demonstrate this, we will create a new class in a new console application.
Create a Console Application
I will assume that you are using either Microsoft Visual Studio or Microsoft C# 2005 Express Edition to develop this program. Launch either of these development environments and elect to create a new project of type, "Console Application". Name the application, "ClassTest".
If you are using another development environment, follow the processes required to create a new console application.
Once the new application has been created, you should have a single code file named 'Program.cs' or similar within the new project. This should contain a class definition and a single method named 'Main'. This method is the first piece of code executed when the software runs. The class definition will be within the code block of a namespace called 'ClassTest'. We will return to this class later.
Add a New Class to the Application
Any number of classes may be added to a namespace within a single code file. However, as this would quickly lead to very large files, it is more readable to separate classes into their own files. We will now add a new class file to the project for a class that will describe vehicles.
Choose 'Add Class...' from the Project menu of Visual Studio or Microsoft C# Express Edition. You will be asked for a name for the new class. Type 'Vehicle' and click the Add button. A new class file is generated with the definition of the class already added. Note that the namespace is the same as the namespace in the original file. You can switch between files using the Solution Explorer to compare the namespaces.
Your new class definition should be similar to that below:
namespace ClassTest
{
class Vehicle
{
}
}
NB: If you are not using Visual Studio, the process for adding a class file may differ slightly.
Instantiating the Class
Although we have not explicitly added any functionality to the class, it can now be instantiated to create objects. These objects will have the standard behaviour of all classes. To demonstrated this, return to the program code file containing the Main method. In this method we will create a new vehicle object and run its ToString method to see the results. As we have not yet defined how ToString should work, this will simply show the fully qualified name.
static void Main(string[] args)
{
Vehicle car = new Vehicle();
Console.WriteLine(car.ToString()); // Outputs "ClassTest.Vehicle"
}
NB: The prefix of ClassTest is simply the name of the namespace of the Vehicle class.
Adding Methods
Public Methods
Public methods are part of the class' 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' 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.
|