Tuesday, October 14, 2008

Creating a Simple Class in C#

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 {}


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
{
}
}



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"
}




No comments: