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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With