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 either "on the stack" or "in-line". Careful programmers can enhance performance through judicious use of structs.
For example, the use of a struct rather than a class for a Point
can make a large difference in the number of allocations. The program below creates and initializes an array of 100 points. With Point
implemented as a class, the program instantiates 101 separate objects – one for the array and one each for the 100 elements.
class Point { public int x, y; public Point() { x = 0; y = 0; } 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 < 100; i++) points[i] = new Point(i, i*i); } }
If Point
is instead implemented as a struct, as in
struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }
then the test program instantiates just one object, for the array. The Point
instances are allocated in-line within the array. Of course, this optimization can be mis-used. Using structs instead of classes can also make your programs fatter and slower, as the overhead of passing a struct instance by value is slower than passing an object instance by reference. There is no substitute for careful data structure and algorithm design.