Why does the parameterless Guid constructor generate an empty GUID?

情到浓时终转凉″ 提交于 2019-12-08 14:40:23

问题


Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?

Is there a particular use for an empty Guid?


回答1:


Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?

Short answer: Because the language/runtime didn't let the designer of the Guid type define a default constructor.

It's not only conventional that the value of a "default-constructed" struct is zero, you simply cannot define a default constructor for a struct. When you say new Guid() the runtime gives you a new object where all the fields are initialized to their default values: http://msdn.microsoft.com/en-us/library/ah19swz4%28VS.71%29.aspx

Some rationale can be found here: http://www.yoda.arachsys.com/csharp/faq/#struct.constructors




回答2:


This behavior is consistent with the rest of the value types in the .Net framework. When "newing up" a value type, a default value is used. This just happens to be the default for Guid similar to Int32's default value of 0.




回答3:


An empty guid is useful to represent the lack of a Guid. Since value types are not nullable (by default yes you can use nullable).

For example I use a Guid as Id properties a lot cause they are real easy to work with. So one way to see if an object has been persisted (Which is when it gets its Id), I can check the value of id against an empty guid.




回答4:


I think it's conventional that the default value, of a struct or of a built-in type, is zero.



来源:https://stackoverflow.com/questions/401198/why-does-the-parameterless-guid-constructor-generate-an-empty-guid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!