What is a difference between “foo is null” and “foo == null”

六月ゝ 毕业季﹏ 提交于 2019-12-18 08:30:18

问题


Is there any difference between: foo is null and foo == null?


回答1:


Short version: For well-behaved types, there is no difference between foo is null and foo == null.

Long version:

When you write foo == null and an appropriate overload of operator == exists, then that's what is called. Otherwise, reference equality is used for reference types and value equality is used for value types.

When you write foo is null for a reference type, this is compiled as if you wrote object.Equals(null, foo) (notice the switched order, it makes a difference). In effect, this performs reference equality comparison between foo and null. For a value type, foo is null does not compile.

This means that if you write a class with operator == that says that some instance of foo is equal to null, then foo == null will give different result than foo is null.

An example showing this:

using System;

public class Foo
{
    public static void Main()
    {
        var foo = new Foo();
        Console.WriteLine(foo == null);
        Console.WriteLine(foo is null);
    }

    public static bool operator ==(Foo foo1, Foo foo2) => true;
    // operator != has to exist to appease the compiler
    public static bool operator !=(Foo foo1, Foo foo2) => false;
}

This code outputs:

True
False

When you overload operator ==, you should make it behave in a reasonable way, which, among other things, means you should not say that foo == null is true for non-null foo. As a side effect of this, under normal circumstances, foo == null and foo is null will have the same value.




回答2:


From the MSDN Docs:

Is operator Checks if an object is compatible with a given type, or (starting with C# 7) tests an expression against a pattern. The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.

== is For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

Summary: No, there isn't in this example. is is normally use if you wanna check the type. In this case it is null. == if you wanna check the value. In this case also null, so both would evaluate to true.



来源:https://stackoverflow.com/questions/44607581/what-is-a-difference-between-foo-is-null-and-foo-null

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