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

Creating Structs with and without new

As shown in lines 46 and 47 of Listing 18.1, a new struct object can, like a class object, be created with the keyword new. As opposed to classes, though, it is also possible to create a struct without using the new keyword. This procedure is demonstrated in Listing 18.3.

Listing 18.3. SimpleTimeSpanStruct.cs
01: using System;
02:
03: public struct TimeSpan
04: {
05:     public uint totalSeconds;
06:
07:     public TimeSpan(uint initialTotalSeconds)
08:     {
09:         totalSeconds = initialTotalSeconds;
10:     }
11: }
12:
13: class Tester
14: {
15:     public static void Main()
16:     {
17:         TimeSpan myTime;
18:
19:         myTime.totalSeconds = 8383;
20:         Console.WriteLine("My time: {0} ", myTime.totalSeconds);
21:     }
22: } My time: 8383  ...

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