1

So I have a Retrieve() function, which either gets me an object or a null (if that object is not found). I'm using an if statement with a boolean attribute of that object. It's set up like this.

if(Retrieve(index).IsForm == true) {}

The issue with this is that if it doesn't find an object, it'll throw a null reference exception. There are some ways around this, of course, but none that I find concise. There's a try...catch, but that seems pointless when I expect the error. I can check if the object is null first, if(Retrieve(index) != null), but that seems like adding needless nesting. Is there a clever way to handle this? I thought of using the null coalescing operator but it doesn't work in this situation.

proseidon
  • 2,235
  • 6
  • 33
  • 57

6 Answers6

2

You can either call the method twice:

if(Retrieve(index) != null && Retrieve(index).IsForm == true) { }

Or you can break the lines apart and store the result before the if:

var result = Retrieve(index);
if(result != null && result.IsForm == true) { }
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

You could write an IsForm function to do both operations for you:

bool IsForm(int index)
{
    var result = Retrieve(index);
    return result != null && result.IsForm;
}

if (IsForm(index))
    ...
Gabe
  • 84,912
  • 12
  • 139
  • 238
1

The Null Object pattern would be helpful here. It keeps your calling code clean but does add an additional class.

class NullWhatever : Whatever
{
    public NullWhatever() { IsForm = false; } 
}


Whatever Retrieve(...) 
{
     ...
     return new NullWhatever();  // instead of null
}
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
1

You could make a Nullable_IsForm extension method. Then you could check for the null condition.

public static class RetrieveExtension
{
    public static bool? Nullable_IsForm(this Retrieve retrieved)
    {
        if(retrieved == null)
        {
            return null;
        }
        else
        {
            return retrieved.IsForm;
        }
    }
}

Then in your code you'd check it against bool values

if(Retrieve(index).Nullable_IsForm == true) 
{}
else if (Retrieve(index).Nullable_IsForm == false) 
{}
else if (Retrieve(index).Nullable_IsForm == null ) 
{}
Mark Rucker
  • 6,952
  • 4
  • 39
  • 65
0

I don't think there is any more concise way to do it, no.

Shortest I can think of is:

if(Retrieve(index)!=null && Retrieve(index).IsForm == true) {}

but I don't like this because it calls Retrieve(index) multiple times. I'd go for

var foo = Retrieve(index);
if(foo!=null && foo.IsForm == true) {}

but that is obviously not doing anything clever or more concise. It is probably more efficeint than some of the alternatives.

Chris
  • 27,210
  • 6
  • 71
  • 92
0

You could put both conditions in the same if:

if(Retrieve(index)!= null && Retrieve(index).IsForm == true) {}

Thanks to short-circuit, if the null-check fails, rest of the expression is not evaluated.

Timoteo Brasil
  • 98
  • 3
  • 12