-2

I have a class "Data" and a subclass "SubData". I want to access a method in SubData.

In order to do something like:

value = Data.SubData.getValue();

I need to make sure that Data!=null and also that SubData!=null.

I would usually do this:

if (Data!=null)
{
   if (Data.SubData!=null)
   {
       value=Data.SubData.Value();
   }
}

However when I want to print a message in case of Data or SubData being null, I need to put the message in two places:

if (Data!=null)
{
   if (Data.SubData!=null)
   {
       value=Data.SubData.Value();
   }
   else
   {
       // MESSAGE
   }  
}
else
{
    // MESSAGE
}

Is there a way of having //Message only in one place? Of course I could set a "showMessage flag" to true and then later have the message appear only in one place, but then I would still set the flag in two places.

1 Answers1

4

You could combine the not null tests into one if statement

if (Data != null || Data.SubData != null)
{
    //Do Whatever
}
else
{
    //Message Evaluation Example
    return Data = null ? "Data is null!" : "Data.SubData is null!";
}

Above I have made a check on both Data and Data.SubData to ensure they are not null, if they are however I use a Ternary Operator to figure out which is null and return the result as a string (don't know what data type you would like to return).

This assumes that both properties will never be null, if they are simply expand the evaluation code.

Tom
  • 351
  • 1
  • 9