How to check object is null or empty in C#.NET 3.5?

后端 未结 7 1072
悲哀的现实
悲哀的现实 2021-02-15 18:26

If objects contains null or empty then how to validate or check the condition for the same?

How to bool check whether object obj is null or

7条回答
  •  清酒与你
    2021-02-15 19:22

    You are getting the null reference because you are executing obj.ToString() which will return obj's ToString() method return value. Problem is that in the previous line you set obj to null so you will get an object reference not... error

    To make your code work you need to do:

    //This will check if it's a null and then it will return 0.0 otherwise it will return your obj.
    double d = Convert.ToDouble(obj ?? 0.0); 
    

    Your code as it is now however will always be 0.0

    Without null coalescing: (??)

    double d = Convert.ToDouble(obj ? 0.0 : obj);    
    

    EDIT

    If I understand correctly from the comments you want to know if the object is null or an empty string. You can do this by casting it to string first instead of calling the ToString method which does something entirely different:

    string objString = (obj as string);
    double d = Convert.ToDouble(string.IsNullOrEmpty(objString) ? "0.0" : objString);      
    

提交回复
热议问题