Specification
Classes and structs have many similarities: structs can implement interfaces and can have the same member types as classes. However, structs differ in several important ways from classes: Structs are value types, not reference types, and structs do not support inheritance. The value of the structure is stored on the stack or inline. Careful programmers can sometimes enhance performance by intelligently using structs.
For example, defining a point as a struct rather than a class can save a lot of memory space at run time. The following program creates and initializes an array of 100 points. For point that is implemented as a class, there are 101 instance objects, because the array requires one, and each of its 100 elements requires one.
Class Point
{
public int x, y;
public point (int x, int y) {
this.x = x;
This.y = y;
}
}
Class Test
{
static void Main () {
Point[] points = new point[100];
for (int i = 0; i < i++)
Points[i] = new Point (i, i*i);
}
}
If you change point to be a struct implementation, such as
struct POINT
{
public int x, y;
public point (int x, int y) {
this.x = x;
This.y = y;
}
}
Only one instance object (the object used for the array) appears. The point instance is allocated inline in the array. This optimization may be misused. Using structs rather than classes also makes your application run slower or consume more memory, because passing a struct instance as a value parameter causes a copy of the structure to be created.