O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required