Thursday, April 28, 2011

Creating a Simple Class in C#

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.

No comments: