Guid.NewGuid() vs. new Guid()

后端 未结 4 1075
耶瑟儿~
耶瑟儿~ 2020-12-04 06:40

What\'s the difference between Guid.NewGuid() and new Guid()?

Which one is preferred?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 07:15

    Guid.NewGuid() creates a new UUID using an algorithm that is designed to make collisions very, very unlikely.

    new Guid() creates a UUID that is all-zeros.

    Generally you would prefer the former, because that's the point of a UUID (unless you're receiving it from somewhere else of course).

    There are cases where you do indeed want an all-zero UUID, but in this case Guid.Empty or default(Guid) is clearer about your intent, and there's less chance of someone reading it expecting a unique value had been created.

    In all, new Guid() isn't that useful due to this lack of clarity, but it's not possible to have a value-type that doesn't have a parameterless constructor that returns an all-zeros-and-nulls value.

    Edit: Actually, it is possible to have a parameterless constructor on a value type that doesn't set everything to zero and null, but you can't do it in C#, and the rules about when it will be called and when there will just be an all-zero struct created are confusing, so it's not a good idea anyway.

提交回复
热议问题