How to set null to a GUID property

Maximus Decimus picture Maximus Decimus · Dec 10, 2013 · Viewed 106.5k times · Source

I have an object of type Employee which has a Guid property. I know if I want to set to null I must to define my type property as nullable Nullable<Guid> prop or Guid? prop.

But in my case I'm not able to change the type of the prop, so it will remains as Guid type and my colleague and I we don't want to use the Guid.Empty.

Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.

I have a mechanism to transform from string.empty to null but I will change many things if the would change to accept a empty guid to null.

Any help please!

Answer

Jon Skeet picture Jon Skeet · Dec 10, 2013

Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.

No. Because it's non-nullable. If you want it to be nullable, you have to use Nullable<Guid> - if you didn't, there'd be no point in having Nullable<T> to start with. You've got a fundamental issue here - which you actually know, given your first paragraph. You've said, "I know if I want to achieve A, I must do B - but I want to achieve A without doing B." That's impossible by definition.

The closest you can get is to use one specific GUID to stand in for a null value - Guid.Empty (also available as default(Guid) where appropriate, e.g. for the default value of an optional parameter) being the obvious candidate, but one you've rejected for unspecified reasons.