2 <clause number="8.7" title="Classes" informative="true">
3 <paragraph>Class declarations define new reference types. A class can inherit from another class, and can implement interfaces. </paragraph>
4 <paragraph>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 (<hyperlink>10.5</hyperlink>), which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the table below. <table_line>Form Intuitive meaning </table_line>
5 <table_line>public Access not limited </table_line>
6 <table_line>protected Access limited to the containing class or types derived from the containing class </table_line>
7 <table_line>internal Access limited to this program </table_line>
8 <table_line>protected </table_line>
9 <table_line>internal </table_line>
10 <table_line>Access limited to this program or types derived from the containing class </table_line>
11 <table_line>private Access limited to the containing type </table_line>
13 <paragraph>The example <code_example><![CDATA[
18 Console.WriteLine("Instance constructor");
20 public MyClass(int value) {
22 Console.WriteLine("Instance constructor");
25 Console.WriteLine("Destructor");
27 public const int MyConst = 12;
28 public int MyField = 34;
29 public void MyMethod(){
30 Console.WriteLine("MyClass.MyMethod");
32 public int MyProperty {
40 public int this[int index] {
45 Console.WriteLine("this[{0}] = {1}", index, value);
48 public event EventHandler MyEvent;
49 public static MyClass operator+(MyClass a, MyClass b) {
50 return new MyClass(a.MyField + b.MyField);
52 internal class MyNestedClass
55 ]]></code_example>shows a class that contains each kind of member. The example <code_example><![CDATA[
59 // Instance constructor usage
60 MyClass a = new MyClass();
61 MyClass b = new MyClass(123);
63 Console.WriteLine("MyConst = {0}", MyClass.MyConst);
66 Console.WriteLine("a.MyField = {0}", a.MyField);
71 Console.WriteLine("a.MyProperty = {0}", a.MyProperty);
74 Console.WriteLine("a[3] = {0}", a[3]);
76 a.MyEvent += new EventHandler(MyHandler);
77 // Overloaded operator usage
80 static void MyHandler(object sender, EventArgs e) {
81 Console.WriteLine("Test.MyHandler");
83 internal class MyNestedClass
86 ]]></code_example>shows uses of these members. </paragraph>