Reputation: 3422
new Guid()
and Guid.Empty
produces the same results (all-0 guid (00000000-0000-0000-0000-000000000000).
var guid = new Guid();
Console.WriteLine(guid);//00000000-0000-0000-0000-000000000000
var emptyGuid = Guid.Empty;
Console.WriteLine(emptyGuid);//00000000-0000-0000-0000-000000000000
Is this a two different manners to do the same thing ? readabilty reasons ? or i'm missing something ?
Upvotes: 3
Views: 2530
Reputation: 1663
Another way of answering the question, through a concrete example :
C# lets you create generic types (templates) that take parameter types.
For example :
public class MyTemplate<T>
You can define all sorts of constraints on T : "Not null", "has a constructor", "is a class", etc.
Like this:
public class MyTemplate<T> where T: notnull, new() // etc.
Extra constraint: You might want to make T not nullable and still return the default value, which might not be "null"!
public class MyTemplate<T> where T: notnull, new() {
public MyTemplate() {
var t = new T(); // If T is a Guid, then this returns Guid.Empty.
//var t = default; // Even if T is a Guid,
// C# will still panic here because
// it's not sure if the "default" of T
// (which you know to be Guid.Empty)
// is nullable or not -- despite you
// having defined T as notnull!
}
}
In conclusion :
You can see for yourself that depending on the context, the same value (Guid.Empty) can spawn from a different concept : In one case it's the result of a parameter-less constructor, in the other case it's a default value.
Since C# cannot predict what you want to do (if you go deep enough into abstraction, then you might want one scenario, or the other, or both!) it implements all the concepts separately , even if they give the same result. So you end up with both new Guid()
and Guid.Empty
, to make use case (every abstraction) happy.
Upvotes: 0
Reputation: 149538
Guid
is a struct
. All structs have an implicit default constructor which initializes all members to their default value. In Guid
, you see that as setting all it's composite members to 0
.
Guid.Empty
simply caches the default value via the invocation of the default constructor:
public struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
}
Upvotes: 9