Defining a Struct
Defining a new value type with the struct keyword is nearly identical to defining a new class as indicated in Syntax Box 18.1; you simply need to substitute the class keyword with the struct keyword.
Syntax Box 18.1 The struct Definition[<Acess_modifier>] struct <Struct_identifier> [: <Interface_list>] { <Struct_members> } |
Recall our TimeSpan class from Chapter 14, “Class Anatomy III: Writing Intuitive Code.” It was represented with a class because we hadn't yet introduced structs at that point. However, it would be more effectively represented by a struct in most cases. This struct alternative is shown in lines 3–40 of Listing 18.1.
Listing 18.1. TimeSpanStruct.cs
01: using System; 02: 03: public struct TimeSpan 04: { ... |
Get C# Primer Plus 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.