Like C and C++, C# includes support for creating structure types. A structure is an aggregate type that combines members of multiple types into a single new type. As with classes, members of a structure are private by default and must be explicitly made public to grant access to clients. A structure is declared using the struct keyword, as shown here:
struct Point { public int x; public int y; }
Structures can’t be inherited.
struct Point { public int x; public int y; } // Not allowed; can't inherit from a struct. class ThreeDPoint: Point { public int z; }
This is in contrast to C++, in which there’s very little real difference between a class and a structure. In C#, structures can inherit from interfaces, but they’re not allowed to inherit from classes or other structures.
Unlike instances of classes, structures are never heap-allocated; they’re allocated on the stack. Staying out of the heap makes a structure instance much more efficient at runtime than a class instance in some cases. For example, creating large numbers of temporary structures that are used and discarded within a single method call is more efficient than creating objects from the heap. On the other hand, passing a structure as a parameter in a method call requires a copy of the structure to be created, which is less efficient than passing an object reference.
Creating an instance of a structure is just like creating a new class instance, as shown here:
Point pt = new Point();
Always use the dot operator to gain access to members of a structure.
pt.y = 5;
Structures can have member functions in addition to member fields. Structures can also have constructors, but the constructor must have at least one parameter, as shown here:
struct Rect { public Rect(Point topLeft, Point bottomRight) { top = topLeft.y; left = topLeft.x; bottom = bottomRight.y; right = bottomRight.x; } // Assumes a normalized rectangle public int Area() { return (bottom - top)*(right - left); } // Rectangle edges int top, bottom, left, right; }
Structures aren’t allowed to declare a destructor.