We’re currently helping a fellow with a codebase he got from a cheap outsourcing company. Many time I’m reading a code sequence I have to read the C# specifications to understand why did they do something. It’s a good challenge and it forces me to learn and relearn.

One example regarding DateTime initialization.

DateTime dtStart = new DateTime();

DateTime is a value type. My first question was “Why would they use the new operator and box this variable?”.
Well, after reading the documentation and running some code, I’ve found out that this was not the case.
In that case the new operator calls the default constructor and the resulted variable is still a value type.
You can execute the code below to check this behavior.

using System;
using System;

namespace NewDateTime
{
    class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // The statement below calls the default DateTime constructor,
            // it is equivalent to var dt = DateTime.MinValue;
            var dt = new DateTime();
            Console.WriteLine("{0}, is boxed:{1}", dt, IsBoxed(dt) ); // Not boxed
                   
            DateTime dt2 = DateTime.MinValue;
            Console.WriteLine("{0}, is boxed:{1}", dt2, IsBoxed(dt2) ); // Not boxed

            object dt3 = new DateTime();
            Console.WriteLine("{0}, is boxed:{1}", dt3, IsBoxed(dt3)); // Boxed.
        }

        /// <summary>
        /// Verifies a value is boxed.
        /// Code sequence courtesy of StackOverflow user jaredpar(
        /// http://stackoverflow.com/users/23283/jaredpar).
        /// </summary>
        public static bool IsBoxed<T>(T value)
        {
            return
                (typeof(T).IsInterface || typeof(T) == typeof(object)) &&
                value != null &&
                value.GetType().IsValueType;
        } 

    }
}

As a side note, there’s a fellow that had to read the code I’ve written some time ago, when I was not quite experienced with C#, and he often said to me that reading my code was a challenge (the same challenge I’m encountering now, as in “what in the name of God are you doing here???”). We do have an interesting job, you cannot get bored 🙂

Advertisements