Checking if an object is null in C#

前端 未结 18 1844
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-11-28 02:47

    Jeffrey L Whitledge is right. Your `dataList´-Object itself is null.

    There is also another problem with your code: You are using the ref-keyword, which means the argument data cannot be null! The MSDN says:

    An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed

    It's also not a good idea to use generics with the type `Object´. Generics should avoid boxing/unboxing and also ensure type safety. If you want a common type make your method generic. Finally your code should look like this:

    public class Foo where T : MyTypeOrInterface {
    
          public List dataList = new List();
    
          public bool AddData(ref T data) {
            bool success = false;
            try {
              dataList.Add(data);                   
              success = doOtherStuff(data);
            } catch (Exception e) {
              throw new Exception(e.ToString());
            }
            return success;
          }
    
          private bool doOtherStuff(T data) {
            //...
          }
        }
    

提交回复
热议问题