Checking if an object is null in C#

前端 未结 18 1845
情深已故
情深已故 2020-11-28 02:12

I would like to prevent further processing on an object if it is null.

In the following code I check if the object is null by either:

if (!data.Equal         


        
18条回答
  •  隐瞒了意图╮
    2020-11-28 02:34

    As of C# 8 you can use the 'empty' property pattern (with pattern matching) to ensure an object is not null:

    if (obj is { })
    {
        // 'obj' is not null here
    }
    

    This approach means "if the object references an instance of something" (i.e. it's not null).

    You can think of this as the opposite of: if (obj is null).... which will return true when the object does not reference an instance of something.

    For more info on patterns in C# 8.0 read here.

提交回复
热议问题