0

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

Salah Akbari
  • 36,933
  • 10
  • 58
  • 91
SPKan
  • 495
  • 2
  • 9
  • 24
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Lance U. Matthews Jun 24 '17 at 18:30
  • 2
    Have you checked how the property getter is build? Maybe it is the getter that is throwing exception not mySalesOrderHeader. – Pablo notPicasso Jun 24 '17 at 19:05

3 Answers3

3

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))
{
...
}
Tuan Le PN
  • 178
  • 7
  • Thanks Tuan. It seems mySalesOrderHeader is not null but I cannot access the mySalesOrderHeader.OrderNumber property. It throws a null reference exception. – SPKan Jun 24 '17 at 19:03
  • @SPKan Then you need to include the code for that property in your question. – mason Jun 24 '17 at 19:04
2

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

if (string.IsNullOrEmpty(mySalesOrderHeader?.OrderNumber))
{
}
Salah Akbari
  • 36,933
  • 10
  • 58
  • 91
  • Thanks @Akbari. but I am using c# 3.0. It seems mySalesOrderHeader is not null but I cannot access the mySalesOrderHeader.OrderNumber property. – SPKan Jun 24 '17 at 19:02
1

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.)

touchofevil
  • 439
  • 2
  • 14