Structs

A struct is similar to a class, with the following key differences:

  • A struct is a value type, whereas a class is a reference type.

  • A struct does not support inheritance (other than implicitly deriving from object, or more precisely, System.ValueType).

A struct can have all the members a class can, except for a parameterless constructor, a finalizer, and virtual members.

A struct is used instead of a class when value-type semantics are desirable. Good examples are numeric types, where it is more natural for assignment to copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiation of an object on the heap; this can incur a useful saving when creating many instances of a type. For instance, creating an array of a value type requires only a single heap allocation.

Struct Construction Semantics

The construction semantics of a struct are as follows:

  • A parameterless constructor that you can’t override implicitly exists. This performs a bitwise-zeroing of its fields.

  • When you define a struct constructor (with parameters), you must explicitly assign every field.

  • You can’t have field initializers in a struct.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.78.237