Why does the is operator return false when given null?

后端 未结 7 1859
小蘑菇
小蘑菇 2020-11-29 23:59

It seems to me that the is operator is a bit inconsistent.

bool Test()
{
    // Returns false, but should return true.
    return null is string         


        
7条回答
  •  甜味超标
    2020-11-30 00:50

    In Java there is an operator that does exactly same thing, but it has much longer name: instanceof. It's very intuitive there that null instanceof String returns false, because null is not an instance of anything, much less a String. So, when using null the Java's version is bit more intuitive.

    However, both of those operators return true when asked to look through entire hierarchy as well. Eg. if instance of String is an Object. And here it's Java that's bit less intuitive (because an instance actually has one, very specific type) and C#'s is is more intuitive (because every String is an Object deep inside).

    Bottom line: if you try to describe pretty advanced logic in one word, you're bound to have few people confused, this way or another. It seems that most people agreed on one meaning and those who did not agree, had to adjust.

提交回复
热议问题