Why does the is operator return false when given null?

后端 未结 7 1735
小蘑菇
小蘑菇 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:56

    the null value

    I've quoted this from your question because it seems to get to the heart of the matter. null isn't a value - it's the absence of a value. The purpose of is to me seems to be to answer the question:

    If I cast E to T, will I successfully get a T ?

    Now, while you can cast null to T without error, after doing so you don't "have a T" - you've still got nothing. So it's not the case that null "is" a T, so is returns false.

    0 讨论(0)
提交回复
热议问题