Chapter 7. Structs

A struct is a simple user-defined type, a lightweight alternative to classes. Structs are similar to classes in that they may contain constructors, properties, methods, fields, operators, nested types, and indexers (see Chapter 9).

There are also significant differences between classes and structs. For instance, structs don't support inheritance or destructors. More important, although a class is a reference type, a struct is a value type. (See Chapter 3 for more information about classes and types.) Thus, structs are useful for representing objects that do not require reference semantics.

The consensus view is that you ought to use structs only for types that are small, simple, and similar in their behavior and characteristics to built-in types.

C and C++ programmers take note: The meaning of C#'s struct construct is very different from C++'s. It permits C# to step outside the single-inheritance Object hierarchy and is particularly useful when interfacing with libraries written in C++.

Structs are somewhat more efficient in their use of memory in arrays (see Chapter 9). However, they can be less efficient when used in collections. Collections expect references, and structs must be boxed. There is overhead in boxing and unboxing, and classes might be more efficient in large collections.

In this chapter, you will learn how to define and work with structs, and how to use constructors to initialize their values.

    Part I: The C# Language