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

7

9

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 Empty

I've code as follows:

class Program
{
    static void Main(string[] args)
    {
        object obj = null;

        double d = Convert.ToDouble(string.IsNullOrEmpty(obj.ToString()) ? 0.0 : obj);
        Console.WriteLine(d.ToString());
    }
}

With this code i'm getting NullReference Exception as Object reference not set to an instance of an object.

Pls help.

Here I'm not getting....

How to validate whether that object is null or Empty without converting into .ToString() ??

Is there an approach to check the same??

Brott answered 17/2, 2012 at 5:50 Comment(10)
You cannot convert a null object to string, thus the error. What's wrong with just checking if(obj != null) ?Whizbang
Why would you call ToString() on an object you know is null, and therefore generates NullReferenceException?Monaural
There is no such thing as an empty object (though there is such a thing as the empty string).Selmner
I think this might just be example code to show the problem...Flavory
Regarding your edit, what do you think an empty object represents?Selmner
@Selmner The empty in IsNullOrEmpty, refers to a string that has no characters in it. It has a length of 0.Flavory
(sorry, I can't edit comments on my phone for some reason) or, perhaps a better question: why do you want to check if the object is null or empty?Selmner
@StefanH I know that, but he's talking about an object, not a string.Selmner
@Selmner That would be becasue a null or empty string cannot be handled by Convert.ToDouble.Flavory
How to check if the object is empty??Brott
F
13

The problem that you are running into is that your object is of type, well, object. In order to evaluate it with string.IsNullOrEmpty, you should pass your object in with the cast to (string)

like so:

static void Main(string[] args)
{
    object obj = null;

    double d = Convert.ToDouble(string.IsNullOrEmpty((string)obj) ? 0.0 : obj);
    Console.WriteLine(d.ToString());
}

This will work fine since you are not explicitly calling .ToString on your (nonexistent) object.

Flavory answered 17/2, 2012 at 5:57 Comment(3)
Assuming that obj is generated by a more complex process than simply setting it to null, the cast would fail in the case where that process produces a real object that isn't a string.Conclusive
Correct, this is assuming that the object in this case would either be null or something that can be converted to a string.Flavory
Technically, this is assuming that the object can be cast to string, not just converted. This failed for me when obj was actually an int, with int.ToString() working, but (string)int failing. It's too bad; I was trying to avoid the extra ToString().Millrun
P
3

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);      
Pepsinate answered 17/2, 2012 at 5:53 Comment(9)
ok....How to validate whether that object is null or empty without convert to .ToString() ??Brott
Like you did except that you don't call the ToString methodPepsinate
@Pepsinate there is no cast to string; calling ToString is not a cast.Selmner
Yeah, it's awesome, just like c# :-)Pepsinate
but this approach doesn't handle empty stringsSelmner
Very first time i'm hearing about null-coalescing operator and makes exciting to know more about the new thing about this operator. Can you give some detail about the importance and benefits of this operator in the situations where i can be used the same with simple and good examples.Brott
If the object obj is empty then how to validate?Brott
@TBohnen.jnr: Still i didn't find your edit or updated comment and still i'm not getting to handle if the object is Empty?Brott
After the bold EDIT in my answer? Do you want to check for an empty String?Pepsinate
L
2
class Program
{
    static void Main(string[] args)
    {
        object obj = DBNull.Value;
        if(obj != DBNull.Value) {
            double d = Convert.ToDouble(obj);
            Console.WriteLine(d.ToString());
        }
    }
}
Lorsung answered 23/10, 2015 at 14:44 Comment(0)
A
1

You can use the ?? operator. It is known as the null-coalescing operator.

Asphaltite answered 17/2, 2012 at 5:55 Comment(2)
Very first time i'm hearing about null-coalescing operator and makes exciting to know more about the new thing about this operator. Can you give some detail about the importance and benefits of this operator in the situations where i can be used the same with simple and good examples.Brott
If the object is empty then how to validate?Brott
L
1

It sounds like what you want to do is this:

object obj = null;
double d;

if (!double.TryParse(Convert.ToString(obj), out d))
{
   d = 0.0;
}

But the question does not make a lot of sense.

Logger answered 17/2, 2012 at 5:57 Comment(0)
C
0

You shouldn't be a bit surprised that you get a NullReferenceException with this code. The offending part is

obj.ToString()

If you wrote

object obj = null;
string s = obj.ToString();

you would expect a NullReferenceException. Since the call to ToString occurs before the call to string.IsNullOrEmpty, the exception is thrown before there is a check for a null or empty string.

Conclusive answered 17/2, 2012 at 5:55 Comment(0)
S
0

Following code could be a safer way of achieving it.

if(obj != null && !string.IsNullOrEmpty(obj.ToString()))
{

}

This code saves us from object being a non-string type.

Serenata answered 9/10, 2016 at 23:37 Comment(3)
Where does the .Value property come from?Amidships
My bad..Updated it..Cheers mate!Serenata
BTW, the OP did ask without converting into .ToString().Amidships

© 2022 - 2024 — McMap. All rights reserved.