Checking if an object is null in C#

前端 未结 18 1793
情深已故
情深已故 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条回答
  • The problem in this case is not that data is null. It is that dataList itself is null.

    In the place where you declare dataList you should create a new List object and assign it to the variable.

    List<object> dataList = new List<object>();
    
    0 讨论(0)
  • 2020-11-28 02:28

    in C# > 7.0 use

    if (obj is null) ...

    This will ignore any == or != defined by the object (unless of course you want to use them ...)

    For not null use if (obj is object) and from C# 9 you can also use if (obj is not null)

    0 讨论(0)
  • 2020-11-28 02:29

    I did more simple (positive way) and it seems to work well.

    Since any kind of "object" is at least an object

    
        if (MyObj is Object)
        {
                //Do something .... for example:  
                if (MyObj is Button)
                    MyObj.Enabled = true;
        }
    
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 02:35

    C# 6 has monadic null checking :)

    before:

    if (points != null) {
        var next = points.FirstOrDefault();
        if (next != null && next.X != null) return next.X;
    }   
    return -1;
    

    after:

    var bestValue = points?.FirstOrDefault()?.X ?? -1;
    
    0 讨论(0)
  • 2020-11-28 02:36

    As of C# 9 you can do

    if (obj is null) { ... }
    

    For not null use

    if (obj is not null) { ... }
    

    If you need to override this behaviour use == and != accordingly.

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