#780 – The Case for Immutable structs

You can run into problems when a struct is mutable.  (E.g. when used as a property, in a collection, or when modifying a struct through a method).

You can avoid problems by being careful about how you use the struct and by being aware of value type semantics (you get a copy of the value-typed object, rather than a reference to it).

You can also avoid problems by making your custom structs immutable.  This means:

  • Exposing the data in the struct exclusively through read-only properties
  • Defining methods that modify the value in the struct to return a new instance of the struct

For an example of this, look at the System.DateTime type, which is a struct.  Its properties all have only a get accessor, so you can’t change them.  And methods that change the value of a DateTime, e.g. AddDays, return a new instance of a DateTime.

Advertisement

#82 – Some Common DateTime and TimeSpan Functions

Here are some of the more common operations that you can perform on DateTime objects:

 DateTime dt = new DateTime(1941, 12, 7);
 dt = dt.AddDays(365);      // 7-Dec-1942 12:00AM
 dt = dt.AddYears(4);       // 7-Dec-1946 12:00AM
 dt = dt.AddMinutes(90);    // 7-Dec-1946 1:30AM

 Console.WriteLine(dt.ToShortDateString());   // 12/7/1946
 Console.WriteLine(dt.ToShortTimeString());   // 1:30 AM
 Console.WriteLine(dt.ToLongDateString());    // Saturday, December 07, 1946
 Console.WriteLine(dt.ToLongTimeString());    // 1:30:00 AM

 string[] fms = dt.GetDateTimeFormats();      // 134 different formats, e.g. 12/7/1946, 12/7/46, 1946-12-07, 07-Dec-46, etc.

 DateTime dt2 = DateTime.Parse("1/1/12");     // 1-Jan-2012

And here are some examples of operations that you can perform on TimeSpan objects:

 TimeSpan ts = new TimeSpan(10, 8, 58);       // 10:08:58
 TimeSpan ts2 = new TimeSpan(-11, 0, 0);      // -11 hrs
 ts = ts.Add(ts2);                            // -00:51:02
 TimeSpan ts3 = ts.Duration();        // 00:51:02  (absolute value)

 TimeSpan ts4 = TimeSpan.FromHours(500);      // 20.20:00:00  (20 days, 20 hrs)
 TimeSpan ts5 = TimeSpan.Parse("1:02:03");    // 01:02:03  (1 hr, 2 min, 3 sec)

 TimeSpan ts6 = ts4 + ts5;     // 20.21:02:03
 TimeSpan ts7 = ts4 - ts5;     // 20.18:57:57

#81 – DateTime and TimeSpan Types

You can use the DateTime type to represent a specific date and time, and the TimeSpan type to represent a particular length of time.

Examples of DateTime values:

 DateTime dt1 = new DateTime(1963, 11, 22);   // 22-Nov-1963
 DateTime dt2 = new DateTime(2001, 9, 11, 9, 59, 0);  // 11-Sep-2001, 9:59AM

Examples of TimeSpan values:

 TimeSpan ts1 = new TimeSpan(33, 30, 29);  // 33 hrs, 30 mins, 29 secs
 TimeSpan ts2 = new TimeSpan(2174, 0, 0, 0);        // 2174 days