Match pattern equal null vs equals null

From Microsoft new-features-in-c-7-0:

public void PrintStars(object o)
{
    if (o is null) return;     // constant pattern "null"
    if (!(o is int i)) return; // type pattern "int i"
    WriteLine(new string('*', i));
}

What is the difference o == nulland o is null?

+6
source share
2 answers

o is nulltranslated into object.Equals(null, o)(you can see it here ).

The code is object.Equals written as :

public static bool Equals(Object objA, Object objB)
{
    if (objA == objB)
    {
        return true;
    }
    if (objA == null || objB == null)
    {
        return false;
    }
    return objA.Equals(objB);
}

therefore at the end will be o == null(first if). Please note that it System.Objectdoes not define operator==, therefore, the one used for reference types is used, which is a reference equality.

, , , o == null ( o a System.Object) , o is null ( )... ?: -)

, o is null o == null ( o a System.Object) .

, o == null object.ReferenceEquals(o, null) ( o a System.Object): -).

, # x is null object.ReferenceEquals(x, null)?. , , , :

int? a = null;
if (a is null) { /* */ }

... "",

+10

"is" == "is" , ==, typeof (type), .

-2

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


All Articles