Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set null to a GUID property

Tags:

c#

guid

nullable

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!

like image 265
Maximus Decimus Avatar asked Dec 10 '13 17:12

Maximus Decimus


People also ask

How do I assign a GUID to null?

You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.

Is GUID empty same as null?

Quoting from an answer from this question. Guid is a value type, so a variable of type Guid can't be null to start with.

Can a GUID be empty?

You can create an Empty Guid or New Guid using a class. yes...you can make the class value as static value...or using that in class..


2 Answers

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.

like image 67
Jon Skeet Avatar answered Sep 20 '22 13:09

Jon Skeet


Guid? myGuidVar = (Guid?)null; 

It could be. Unnecessary casting not required.

Guid? myGuidVar = null; 
like image 21
A.S Avatar answered Sep 19 '22 13:09

A.S