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)
Beginning with C# 7.1, you can use default literal to produce the default value of a type when the compiler can infer the expression type.
Console.Writeline(default(Guid));
// ouptut: 00000000-0000-0000-0000-000000000000
Console.WriteLine(default(int)); // output: 0
Console.WriteLine(default(object) is null); // output: True
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default
Check Nullable<T>.HasValue
if(!SomeProperty.HasValue ||SomeProperty.Value == Guid.Empty)
{
//not valid GUID
}
else
{
//Valid GUID
}
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}
You should use the HasValue
property:
SomeProperty.HasValue
For example:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
Note that HasValue
will return true for an empty Guid
.
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;
Source: Stackoverflow.com