18. Structs


Chapter 18. STRUCTS

You will learn about the following in this chapter:

  • What a struct is

  • The similarities and differences between classes and structs

  • How to define and use structs

  • Boxing and unboxing structs

According to Chapter 6, "Types, Part I: The Simple Types," C#'s types can be divided into reference types (such as string, Elevator, and Car) and value types (such as short, int and the other simple types). Until now, we have designed our own reference types with the class keyword to form classes. In a similar way, we can define our own value types by using the struct keyword to form structs as discussed in this chapter.

Classes are useful to represent most of the objects in a typical C# program. However, structs represent a lightweight alternative to classes, which, as the simple intrinsic types (byte, short, int and so on) demonstrate, are preferred over classes when we need to construct types that are simple and only need to represent one or a few related data items. Typical examples where structs usually have an edge over classes are when we need to represent

  • A point in a coordinate system consisting of just two values, x and y

  • A temperature

  • A time span

  • A fraction consisting of two numbers, a numerator and a denominator

Structs and classes have many similarities and a few significant differences. Like classes, structs can contain methods, properties, indexers, constructors, data members, operator methods, nested types, and they can implement interfaces. As opposed to classes, they don't support inheritance (but they still implicitly inherit from System.Object). They don't contain destructors, and parts of how their constructors are implemented are different.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net