21 Jul
2007

The Mysterious System.Guid

Category:UncategorizedTag: , :

I have some objects I am serializing that have an ID property.  The ID property is a GUID and I got to looking at the nature of the System.Guid class during this project.

I gots me some questions.

Constructor Madness

Why is there a default constructor AND a static creator? Both of the following code lines are valid.

this.ID = new Guid();

and

this.ID = Guid.NewGuid();

Also available is the Guid.Empty field, which is a GUID initialized to all zero values. It turns out, you get an “empty” GUID when using the default constructor instead of the static initializer. This causes us to do things like check parameter GUIDs for emptiness in function parameter checking.  That’s a little irritating and would be wholly unnecessary if the new Guid() return an actual initialized GUID.

I am convinced that the reason new Guid() exists is to support serialization.  Without the default constructor, we could not serialize the object.  OK, fine.  Then why the static initializer? Why not just return a real GUID from the default constructor?  There isn’t a factory pattern at work here.  I don’t get it. Anyone?

Technorati tags: , , , ,

3 thoughts on “The Mysterious System.Guid

  1. Guid is a struct, so you get the default constructor whether you want it or not 🙂

    I’m going to guess that NewGuid() is maybe computationally expensive, so you don’t want to go through that process in the default constructor if all you’re going to do is set the value manually anyway.

    I’ve run into a case where the method that NewGuid() uses to create a Guid isn’t the one that I need in an application – for example Guids used as a primary key in a sqlserver database require special handling:

    http://codebetter.com/blogs/scott.bellware/archive/2006/12/27/156671.aspx

    Just two cents..
    Tony

  2. This makes as much sense as anything else.

    The reason this is so compelling to me is that I am building a class for an opensource project that has similar requirements for default construction, serialization, and “emptiness”. I basically built it like the Guid class and I dont like it because the proper usage isnt clear to the person using the class.

  3. It would be a very bad design if the default for a type was a totally unpredictable value… ironically, the most unpredictable value possible

Comments are closed.