A canonical class declaration defines a new reference type. A class can inherit from another class and can implement multiple interfaces.
Class members can include: constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and nested type declarations. Each member has an associated accessibility that controls the range of program text that can access that member. There are five possible forms of accessibility. These forms are summarized in the following table.
Form intuitive meaning
Public
Access is not restricted.
Protected
Access is limited to the class to which the member belongs, or to a type derived from the class.
Internal
Access is limited to this program.
protected internal
Access is limited to this program or types derived from the class to which the member belongs.
Private
Access is limited to the type to which the member belongs.
Example
Using System;
Class MyClass
{
Public MyClass () {
Console.WriteLine ("Instance constructor");
}
public MyClass (int value) {
MyField = value;
Console.WriteLine ("Instance constructor");
}
~myclass () {
Console.WriteLine ("destructor");
}
public const int MYCONST = 12;
public int MyField = 34;
public void MyMethod () {
Console.WriteLine ("Myclass.mymethod");
}
public int MyProperty {
get {
return MyField;
}
set {
MyField = value;
}
}
public int This[int index] {
get {
return 0;
}
set {
Console.WriteLine ("this[{0}] = {1}", index, value);
}
}
public event EventHandler MyEvent;
public static MyClass operator+ (MyClass A, MyClass b) {
return new MyClass (A.myfield + B.myfield);
}
Internal class Mynestedclass
{}
}
Shows a class that contains members with various accessibility features. Example
Class Test
{
static void Main () {
Instance constructor Usage
MyClass a = new MyClass ();
MyClass B = new MyClass (123);
Constant usage
Console.WriteLine ("Myconst = {0}", Myclass.myconst);
Field usage
a.myfield++;
Console.WriteLine ("A.myfield = {0}", A.myfield);
Method usage
A.mymethod ();
Property usage
a.myproperty++;
Console.WriteLine ("A.myproperty = {0}", A.myproperty);
Indexer usage
A[3] = a[1] = a[2];
Console.WriteLine ("a[3] = {0}", a[3]);
Event usage
A.myevent + = new EventHandler (MyHandler);
Overloaded operator usage
MyClass C = a + B;
}
static void MyHandler (object sender, EventArgs e) {
Console.WriteLine ("Test.myhandler");
}
Internal class Mynestedclass
{}
}
Shows the usage of these members.