SPKan
SPKan

Reputation: 555

Check the objects properties are null

I have a class which gets a object from the external system. I want to validate my parameters are correct. It seems my object is not null even though I sent a wrong value to the service.Basically I want to check mySalesOrderHeader contains a valid order number or not.

For example, if (mySalesOrderHeader != null) { Do My Stuff} I am checking this condition once mySalesOrderHeader is retrieved from the system. Inside my if condition[Where {Do My Stuff}] is located, I am accessing its property and checking its existence.

if(string.IsNullOrEmpty(mySalesOrderHeader.OrderNumber)){}

But in here it throws a null reference exception. How can I check a property is null, if my parent object does not have the value in it.

Note: I am using C# 3.0

Upvotes: 0

Views: 147

Answers (3)

touchofevil
touchofevil

Reputation: 613

You can try below snippet. Its easy and clean and would work with C# 3.0

if (mySalesOrderHeader != null)
{
    // are you sure you're not missing out '!' operator at string null or empty check?
    if  (!string.IsNullOrEmpty(mySalesOrderHeader.OrderNumber))
    {
        // logic if order number has some value
    }
}

Also only check for parent object once its retrieved (to me it seemed from your question that the null check is bypassed due to some reason.)

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39946

Use Null-Conditional operator (C#6 feature). It tests for null before performing a member access Like this:

if (string.IsNullOrEmpty(mySalesOrderHeader?.OrderNumber))
{
}

Upvotes: 2

Tuan Le PN
Tuan Le PN

Reputation: 384

If the variable mySalesOrderHeader is null, you cannot access its properties otherwise exception will be thrown. So, you should check mySalesOrderHeader first.

if  (string.IsNullOrEmpty(mySalesOrderHeader != null ? mySalesOrderHeader.OrderNumber : null))
{
...
}

Upvotes: 3

Related Questions