Extend an “object” with a null check more readable than ReferenceEquals

I tried extending the "object" to allow a more readable check if the object is null.

Now it object.ReferenceEquals really checks the null object (rare times that it will not apply, since the operator ==can be redefined, the method object.Equals(null)can also be redefined).

But object.ReferenceEquals(null, obj);not too readable, is it? ... So, I thought: why not write an extension method for System.objectthat will provide this check withobject.IsNull(obj);

I tried:

public static class MyExtClass
{
    // the "IsNull" extension to "object"  
    public static bool IsNull(this object obj)
    {
        return object.ReferenceEquals(obj, null);
    }
}

public SomeOtherClass
{
     public static void TryUsingTheExtension()
     {
          object obj;

          // Why does this line fail? the extension method is not recognized
          // I get: 'object' does not contain a definition for "IsNull"
          bool itIsANull = object.IsNull(obj);
     }
}

What did I miss?

+4
source share
6 answers

Try

bool itIsANull = obj.IsNull();
+2
source

, , . bool itIsANull = object.IsNull(obj); , , . :

bool itIsANull = (new object()).IsNull();

MyExtClass, ( mscore.lib):

MyExtClass.IsNull(new object());

P.S. , - . , , . , Intellisense .

mscorelib . - . , Intellisense , , 'this' . - , "" , . , obj.MyExtMethod() , Helper.MyExtMethod(obj); ( ),

+2

, , .

object.IsNull(), , .

:

// either the static method on the class
MyExtClass.IsNull(obj);

// or using the actual feature of extension methods
obj.isNull();

Since it is an extension method, the last form will be automatically converted to the first at compile time.

+1
source

You call the extension method on the object itself. Instead, you should call metd on the instance -

bool itIsANull = obj.IsNull()
+1
source

Try:

    class Program
    {
        static void Main(string[] args)
        {
            var o = new object();
            if (o.IsNull())
            {
                Console.Write("null");
            }
        }
    }

    public static class Request
    {
        public static bool IsNull(this object obj)
        {
            return ReferenceEquals(obj, null);
        }
    }
+1
source
public static class MyExtClass
    {
        // the "IsNull" extension to "object"  
        public static bool IsNull(this object obj)
        {
            return object.ReferenceEquals(obj, null);
        }

    }

    public class SomeOtherClass
    {
        public static void TryUsingTheExtension()
        {
            object obj =null;

            bool itIsANull = obj.IsNull();
        }

    }
+1
source

Source: https://habr.com/ru/post/1599455/


All Articles