Classes are declared using the keyword class. The declaration takes the form:
[attributes] [modifiers] class identifier [:base-list] { class-body }[;]
where:
Unlike C++, only single inheritance is allowed in C#. In other words, a class can inherit implementation from one base class only. However, a class can implement more that one interface.
The access levels protected and private are only allowed on nested classes.
A class can contain declarations of the following members:
The following example demonstrates declaring class fields, constructors, and methods. It also demonstrates object instantiation and printing instance data. In this example, two classes are declared, the Kid
class, which contains two private fields (name
and age
) and two public methods. The second class is MainClass
, used for data processing.
// class example using System; public class Kid { private int age; private string name; // Default constructor public Kid() { name = "N/A"; } // Constructor: public Kid(string name, int age) { this.name = name; this.age = age; } // Printing method: public void PrintKid() { Console.WriteLine("{0}, {1} years old.", name, age); } } public class MainClass { public static void Main() { // Create objects // Objects must be created using the new operator: Kid kid1 = new Kid("Craig", 11); Kid kid2 = new Kid("Sally", 10); // Create an object using the default constructor: Kid kid3 = new Kid(); // Display results: Console.Write("Kid #1: "); kid1.PrintKid(); Console.Write("Kid #2: "); kid2.PrintKid(); Console.Write("Kid #3: "); kid3.PrintKid(); } }
Kid #1: Craig, 11 years old. Kid #2: Sally, 10 years old. Kid #3: N/A, 0 years old.
Notice, in the preceding example, that the private fields (name
and age
) can only be accessed through the public methods of the Kid
class. For example, you cannot print the kid's name, from the Main
method, using a statement like this:
Console.Write(kid1.name); // Error
However, it is possible to do that if the Main
method is a member of the Kid
class.
Notice also that the private modifier is the default modifier for class members. If you remove the modifier, you still get private members. For more information on access level modifiers, see Access Modifiers.
Notice also that for the object created using the default constructor (kid3
), the age field was initialized to zero.
For more information on classes, see §10 in the language reference.