venkat venkat - 1 month ago 24
ASP.NET (C#) Question

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

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??

Answer

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.