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

前端 未结 7 1360
不思量自难忘°
不思量自难忘° 2020-12-24 00:19

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

7条回答
  •  难免孤独
    2020-12-24 00:47

    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 :)

提交回复
热议问题