Unlike classes, a
struct is a value type, and is created on the local stack and not on the managed heap, by default. This means that once the specific stack goes out of scope, the
struct is de-allocated. Contained reference types of de-allocated
structs are also swept, once the GC determines they are not longer referenced to by the
structs cannot inherit and cannot be bases for inheritance, they are implicitly sealed, and also cannot include
protected members. However, a
struct can implement an interface, as classes do.
Declaring a struct
structinstance fields can be set via a parametrized constructor or individually after
Private members can only be initialized by the constructor.
structdefines a sealed type that implicitly inherits from System.ValueType.
Structs cannot inherit from any other type, but they can implement interfaces.
Structs are copied on assignment, meaning all data is copied to the new instance and changes to one of them are not reflected by the other.
A struct cannot be
null, although it can used as a nullable type:
Structs can be instantiated with or without using the
newoperator must be used in order to use an initializer:
A struct can declare everything a class can declare, with a few exceptions:
- A struct cannot declare a parameterless constructor.
structinstance fields can be set via a parameterized constructor or individually after
structconstruction. Private members can only be initialized by the constructor.
- A struct cannot declare members as protected, since it is implicitly sealed.
- Struct fields can only be initialized if they are const or static.
Struct implementing interface
If we use a struct with its constructor, we aren't going to have problems with unassigned field (each unassigned field has null value).
Unlike classes, a struct doesn't have to be constructed, i.e. there is no need to use the new keyword, unless you need to call one of the constructors. A struct does not require the new keyword because is a value-type and thus cannot be null.
Structs are copied on assignment
Sinse structs are value types all the data is copied on assignment, and any modification to the new copy does not change the data for the original copy. The code snippet below shows that
p1 is copied to
p2 and changes made on
p1 does not affect