1

Current version of C# (higher than 7.1) has next two ways to check that the variable is null:

// first one
object.Equals(a, null);

// second one
a is null;

I wonder, what advantages of each way are. Is there any special cases for use both of them?

doctor
  • 11
  • 1

1 Answers1

0

Equals proves for identity, that means the object are EXACT the same. You could override Equals, in this case you can check their properties. (in case of object.Equals, you prove for identity).


The is expression is true if expr isn't null, and any of the following is true: (SRC: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is)

expr is an instance of the same type as type.

expr is an instance of a type that derives from type. In other words, the result of expr can be upcast to an instance of type.

expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its declaration. The runtime type of a variable is the type of the instance that is assigned to that variable.

expr is an instance of a type that implements the type interface.

Here you can find how to override Equals: https://learn.microsoft.com/de-de/dotnet/api/system.object.equals?view=netframework-4.8

Here some examples:


    public class Word
{
    public string Name;

    public Word(string name)
    {
        Name = name;
    }

    //Euqals is no overriden
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }


    public class OtherClass
    {
        public OtherClass()
        {
            Word word = new Word("word");
            Word otherWord = new Word("word");
            string a = null;

            var r = a == null; //true
            var r2 = object.Equals(a, null);//true      
            var r3 = word.Name is string; //true
            var r4 = word.Name is Word; //false
            var r5 = word.Equals(otherWord); //false
        }
    }

In case you override equals in your class:


public class Word
{
    public string Name;

    public Word(string name)
    {
        Name = name;
    }

    //Override Equals
    public override bool Equals(object obj)
    {
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            Word thisWord = (Word) obj;
            return (Name == thisWord.Name) /* && (Other properties)*/;
        }
    }


    public class OtherClass
    {
        public OtherClass()
        {
            Word word = new Word("word");
            Word otherWord = new Word("word");
            string a = null;

            var r = a == null; //true
            var r2 = object.Equals(a, null);//true      
            var r3 = word.Equals(otherWord); //true
        }
    }
Adrian Efford
  • 473
  • 3
  • 8