Skip to Main Content
Programming C#
book

Programming C#

by Jesse Liberty
July 2001
Intermediate to advanced content levelIntermediate to advanced
688 pages
16h 14m
English
O'Reilly Media, Inc.
Content preview from Programming C#

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 structors, 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] struct identifier [:interface-list]
{ struct-members }

Example 7-1 illustrates the definition of a struct. Location represents a point on a two-dimensional surface. Notice that ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming C#, Second Edition

Programming C#, Second Edition

Jesse Liberty
Programming C# 12

Programming C# 12

Ian Griffiths
Programming C# 8.0

Programming C# 8.0

Ian Griffiths

Publisher Resources

ISBN: 0596001177Supplemental ContentCatalog PageErrata