質問

I am learning about GUID in C#. While reading, I have come across these two things such as

1. Guid obj = new Guid();
2. Guid obj = Guid.NewGuid();

I read, the first one always be 16 byte with all 0. The second one will makes an actual GUID with a unique value. Then What is the actual purpose of new Guid();? And When to use it?

役に立ちましたか?

解決

Guid is a value type. The compiler accepts new T() for all value types T, with exactly the same meaning as default(T). A value type cannot prevent this even if default(T) is a nonsensical value for this specific type.

So, to answer your question, new Guid() isn't allowed because it's useful, it's allowed for technical reasons only. You shouldn't ever use it. If you really want an all-zero Guid, default(Guid) or Guid.Empty are far better for readability.

他のヒント

I guess the purpose is NOT the parameterless constructor, but the constructor overloads taking an existing GUID.

There are also several cases where you need a parameterless constructor like for deserialization.

You can have a look at GUID implementation here:

http://referencesource.microsoft.com/#mscorlib/system/guid.cs#b622ef5f6b76c10a

Like already said, it is structural type and needs to have default value.

Then What is the actual purpose of new Guid();?

new Guid() willbe used to intialise the Guid object by calling the constructor.

there is a static method NewGuid() in GUID structure which will return you the actual GUID by calling Guid.NewGuid()

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top