Pattern matching equal null vs is null

后端 未结 3 612
有刺的猬
有刺的猬 2021-01-02 09:49

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


        
3条回答
  •  渐次进展
    2021-01-02 10:14

    Since the answer of @xanatos is outdated (but that is only mentioned at the very end) I'm writing a new one, because I wanted to know this as well and researched it.

    In short: if you don't overload the == operator, then o == null and o is null are the same.
    If you do overload the == operator, then o == null will call that, but o is null won't.

    o is null always does the same as ReferenceEquals(o, null), i.e. it only checks if the value is null, it doesn't call any operators or Equals methods.

    Longer answer: here is a SharpLab sample that showcases the various ways to check for null.

    If you view the result in IL form you see that:

    • is null and ReferenceEquals result in the same code
    • o == null will call the overloaded operator==
    • object.Eqauls(o, null) calls that method
    • if you comment the operator== in class C you will see that o == null now produces the same code as o is null

提交回复
热议问题