Why isn't there a Guid.IsNullOrEmpty() method

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

This keeps me wondering why Guid in .NET does not have IsNullOrEmpty() method (where empty means all zeros)

I need this at several places in my ASP.NET MVC code when writing the REST API.

Or am I missing something because nobody on the Internet has asked for the same?

回答1:

Guid is a value type, so a variable of type Guid can't be null to start with. If you want to know if it's the same as the empty guid, you can just use:

if (guid == Guid.Empty) 


回答2:

For one thing, Guid is not nullable. You could check:

myGuid == default(Guid) 

which is equivalent to:

myGuid == Guid.Empty 


回答3:

Here is a simple extension method for a nullable Guid.

///  /// Determines if a nullable Guid (Guid?) is null or Guid.Empty ///  public static bool IsNullOrEmpty(this Guid? guid) {   return (!guid.HasValue || guid.Value == Guid.Empty); } 

UPDATE

If you really wanted to use this everywhere you could write another extension method for a regular Guid. It can never be null, so some people won't like this... but it serves the purpose you are looking for and you don't have to know whether you are working with Guid? or Guid (nice for re-factoring etc.).

///  /// Determines if Guid is Guid.Empty ///  public static bool IsNullOrEmpty(this Guid guid) {   return (guid == Guid.Empty); } 

Now you could use someGuid.IsNullOrEmpty(); in all cases, whether you are using Guid or Guid?.

Like I said, some people will complain about the naming because IsNullOrEmpty() implies that the value could be null (when it can't). If you really wanted to, come up with a different name for the extensions like IsNothing() or IsInsignificant() or whatever :)



回答4:

You can make an extension method to Guid to add IsEmpty functionality:

public static class GuidEx {     public static bool IsEmpty(this Guid guid)     {         return guid == Guid.Empty;     } }  public class MyClass {     public void Foo()     {         Guid g;         bool b;          b = g.IsEmpty(); // true          g = Guid.NewGuid();          b = g.IsEmpty; // false          b = Guid.Empty.IsEmpty(); // true     } } 


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