Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Nullable Guid is empty in c#

Tags:

c#

guid

nullable

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.

What then if I see this?

public Nullable<System.Guid> SomeProperty { get; set; } 

how should I check if this is null? Like this?

(SomeProperty == null) 

or like this?

(SomeProperty == Guid.Empty) 
like image 294
Saturnix Avatar asked Jul 17 '13 07:07

Saturnix


People also ask

How do I know what my Guid is worth?

You can compare a GUID with the value of the Guid. Empty field to determine whether a GUID is non-zero. The following example uses the Equality operator to compare two GUID values with Guid. Empty to determine whether they consist exclusively of zeros.

Is a Guid Nullable?

Like other value types, GUID also has a nullable type which can take null value.

What does empty Guid look like?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - " 00000000-0000-0000-0000-000000000000 ". In newer C# versions, default(Guid) and default are the same, too.

Is Empty Guid valid?

Empty is "{00000000-0000-0000-0000-000000000000}" which located the representation range of a guid, but we just marked is as Empty, so it is safe to use (someGuid ==Guid. Empty).


2 Answers

If you want be sure you need to check both

SomeProperty == null || SomeProperty == Guid.Empty 

Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}

like image 113
Sir l33tname Avatar answered Sep 20 '22 01:09

Sir l33tname


SomeProperty.HasValue I think it's what you're looking for.

See DevDave's or Sir l33tname's answer instead.

EDIT : btw, you can write System.Guid? instead of Nullable<System.Guid> ;)

like image 20
dotixx Avatar answered Sep 21 '22 01:09

dotixx