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