Structs
A struct is similar to a class, with the following major differences:
A class is a reference type, while a struct is a value type. Consequently, structs are typically used to express simple types, in which value-type semantics are desirable (e.g., an assignment copies a value rather than a reference).
A class fully supports inheritance, whereas a struct can inherit only from an object and is implicitly sealed (in the runtime, structs actually inherit from
System.ValueType). Both classes and structs can implement interfaces.A class can have a destructor, and a struct cannot.
A class can define a custom parameterless constructor and initialize instance fields, while a struct cannot. The default parameterless constructor for a struct initializes each field with a default value (effectively zero). If a struct declares a constructor(s), then all of its fields must be assigned in that constructor call.
Here is a simple struct declaration:
struct Point {
public int x, y;
}To create a
struct,
you can use the new
operator, which
will initialize all the struct members to their defaults (zero in the
case of x and y). If you do not
use the new operator, you will need to initialize
the struct members yourself. You can also use array declaration
syntax to create an array of structs:
Point p1 = new Point( ); Point p2; p2.x = p2.y = 0; Point[] points = new Point[3];
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access