Thursday, June 20, 2013

Nullabe Guid?

I saw this today:
    if (myObject.ResourceValue != null)
    {
        otherData.Value = myObject.ResourceValue.ToString();
    }

and wondered if it is possible to get to this situation. So I tried it out myself and found that you will never have a null, non-nullable guid. See below:
namespace ScratchConsole
{
    public class Haha
    {
        private Guid _value;

        public Guid Null { get { return _value; } }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            Guid? test = null;
            //Guid data = test.Value; // throws an exception.
            //Guid data2 = null; // won't compile
            Guid data3;
            //Console.WriteLine(data3.ToString()); // won't compile, unassigned variable.

            Haha ha = new Haha();

            Console.WriteLine(ha.Null.ToString()); // outputs "00000000-0000-0000-0000-000000000000"
        }
    }
}

It seems that instead you should always check for an empty guid. Like so:
    if (myObject.ResourceValue != Guid.Empty)
    {
        otherData.Value = myObject.ResourceValue.ToString();
    }