O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required