Checking if an object is null in C#

前端 未结 18 1870
情深已故
情深已故 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:22

    No, you should be using !=. If data is actually null then your program will just crash with a NullReferenceException as a result of attempting to call the Equals method on null. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals method as you never know how Equals has been implemented.

    Your program is crashing because dataList is null as you never initialize it.

提交回复
热议问题