disable broken tests on net_4_0
[mcs.git] / docs / ecma334 / 8.8.xml
blob8f61f577bd96ecb6fa3893b50d2cea07358159e8
1 <?xml version="1.0"?>
2 <clause number="8.8" title="Structs" informative="true">
3   <paragraph>The list of similarities between classes and structs is long-structs can implement interfaces, and can have the same kinds of members as classes. Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored &quot;on the stack&quot; or &quot;in-line&quot;. Careful programmers can sometimes enhance performance through judicious use of structs. </paragraph>
4   <paragraph>For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at run time. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements. <code_example><![CDATA[
5 class Point  
6 {  
7    public int x, y;  
8    public Point(int x, int y) {  
9       this.x = x;  
10       this.y = y;  
11    }  
12 }  
13 class Test  
14 {  
15    static void Main() {  
16       Point[] points = new Point[100];  
17       for (int i = 0; i < 100; i++)  
18       points[i] = new Point(i, i*i);  
19    }  
20 }  
21 ]]></code_example></paragraph>
22   <paragraph>If Point is instead implemented as a struct, as in <code_example><![CDATA[
23 struct Point  
24 {  
25    public int x, y;  
26    public Point(int x, int y) {  
27       this.x = x;  
28       this.y = y;  
29    }  
30 }  
31 ]]></code_example>only one object is instantiated-the one for the array. The Point instances are allocated in-line within the array. This optimization can be misused. Using structs instead of classes can also make an application run slower or take up more memory, as passing a struct instance by value causes a copy of that struct to be created. </paragraph>
32 </clause>