Structs

               attributes? unsafe? access-modifier?
new?
struct struct-name [: interface+]?
{ struct-members }

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., assignment copies a value rather than a reference).

  • A class fully supports inheritance (see Chapter 5), 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.

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.