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.
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.
Defining Structs
The syntax for declaring a struct is almost identical to that for a class:
[attributes
] [access-modifiers
] structidentifier
[:interface-list
] {struct-members
}
Example 7-1 illustrates the definition of a struct.
Location
represents a point on a two-dimensional surface. Notice that ...
Get Programming C#, Second Edition 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.