What is the right checking:
Guid value;
// ...
if (value != Guid.Empty)
or
if (value != default(Guid))
I think the 2nd but can't explain why.
default ( TSource ) if source is empty or if no element passes the test specified by predicate ; otherwise, the first element in source that passes the test specified by predicate .
The default keyword returns the "default" or "empty" value for a variable of the requested type. For all reference types (defined with class , delegate , etc), this is null . For value types (defined with struct , enum , etc) it's an all-zeroes value (for example, int 0 , DateTime 0001-01-01 00:00:00 , etc).
Since Guid.Empty == default(Guid)
it does not really matter, but I would prefer Guid.Empty
for readability.
Guid.Empty
is equivalent to new Guid()
, which is also equivalent to default(Guid)
.
When you decompile Guid
structure, it seems;
public static readonly Guid Empty = new Guid();
Since Guid
is a struct
, from Default Values Table;
The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Since field types of Guid
are, short
, int
, byte
, (and this types default value is 0
), when we use default(Guid)
we get a Guid
with all fields are 0
.
From Guid.Empty Field
A read-only instance of the Guid structure whose value is all zeros.
When we write this code;
Console.WriteLine(default(Guid));
Console.WriteLine(new Guid());
outputs;
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000
If you care about readability (which I think you should) Guid.Empty
seems better to me.
The both are the same!
Guid.Empty
is a readonly field of Guid, having the value {00000000-0000-0000-0000-000000000000}
.
With default(Guid)
the compile creates a constant value, having {00000000-0000-0000-0000-000000000000}
.
In both cases your value is compared to another value somewhere in memory.
Use Guid.Empty
for readability.
Use default(T)
when you are working with generics.
I would say the second purely because you have the record in an uninitialized state, therefore, it will contain the default value. You are checking whether the variable is in a default state, not whether it's empty - 2 different checks (IMO).
Guid.Empty
is the equivalent to default(Guid)
in .NET so from a technical point of view it doesn't matter, however, comparing to Guid.Empty
gives me the impression that your checking for a particular value, not whether the record is in a default state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With