| title | class (C# Reference) | ||
|---|---|---|---|
| ms.date | 07/18/2017 | ||
| ms.prod | .net | ||
| ms.technology |
|
||
| ms.topic | article | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
||
| ms.assetid | b95d8815-de18-4c3f-a8cc-a0a53bdf8690 | ||
| caps.latest.revision | 30 | ||
| author | BillWagner | ||
| ms.author | wiwagn |
Classes are declared using the keyword class, as shown in the following example:
class TestClass
{
// Methods, properties, fields, events, delegates
// and nested classes go here.
}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 than one interface. The following table shows examples of class inheritance and interface implementation:
| Inheritance | Example |
|---|---|
| None | class ClassA { } |
| Single | class DerivedClass: BaseClass { } |
| None, implements two interfaces | class ImplClass: IFace1, IFace2 { } |
| Single, implements one interface | class ImplDerivedClass: BaseClass, IFace1 { } |
Classes that you declare directly within a namespace, not nested within other classes, can be either public or internal. Classes are internal by default.
Class members, including nested classes, can be public, protected internal, protected, internal, private, or private protected. Members are private by default.
For more information, see Access Modifiers.
You can declare generic classes that have type parameters. For more information, see Generic 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 first class, Child, contains two private fields (name and age), two public constructors and one public method. The second class, StringTest, is used to contain Main.
[!code-csharpcsrefKeywordsTypes#5]
Notice that in the previous example the private fields (name and age) can only be accessed through the public method of the Child class. For example, you cannot print the child's name, from the Main method, using a statement like this:
Console.Write(child1.name); // ErrorAccessing private members of Child from Main would only be possible if Main were a member of the class.
Types declared inside a class without an access modifier default to private, so the data members in this example would still be private if the keyword were removed.
Finally, notice that for the object created using the default constructor (child3), the age field was initialized to zero by default.
[!INCLUDECSharplangspec]
C# Reference
C# Programming Guide
C# Keywords
Reference Types