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.
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
When a new struct object is created without the new keyword, none of the constructors for this struct are called. Instead, all data members must be initialized by assigning the initialization values directly to the data members through the struct object name, as in line 19. It is not possible to perform these initializations through properties or methods, because none of the function members can be called until all data members have been initialized. Consequently, the data members must be declared public, as shown in line 5.