-1

How can I check for null without using if statement, in C#?

public class Bar {
 public void foo() {

  var discount = _discountService.GetDiscountById(discountId);
  //this is anti pattern . is there any other way ?
  if (discount == null)
      throw new ArgumentException("Discount could not be loaded");

  //main logic of methods continues here 
 }
}
7
  • 2
    Who says conditional operations are "code smell[s]"? The only time it's a problem is for GPU shaders and then it's for performance reasons not cosmetic
    – user585968
    Oct 9, 2018 at 5:29
  • it is code smell because you have to write test for each condition , so managing test would be hard .
    – Arash
    Oct 9, 2018 at 5:35
  • 2
    @Arash Anytime you want to do something different depending on a condition (in this case, whether something is null), you will have branches. If you want to eliminate any "conditionals" then your code must do "one thing".
    – Sweeper
    Oct 9, 2018 at 5:53
  • After reading this post again, I'm not sure whether checking for null constitutes a code smell. You aren't really performing a branch based on the type but rather that an object has valid state. You can't very well proceed if inputs aren't valid. What's probably more interesting is why GetDiscountById can return null in the first place? Simply return decimal 0
    – user585968
    Oct 9, 2018 at 6:44
  • and what is that negative vote for ?
    – Arash
    Oct 9, 2018 at 7:56

3 Answers 3

1

Branching is not always a code smell. It usually considered a code smell when you are branching over types, which could be solved with polymorphism.

Here you could consider what the behavior should be of GetDiscountById when the discount is not found. If you have that method throw instead at null, you only have to test the id not found case in the discount service class and not everywhere where you call it, because you can always expect it to return succesfully or throw.

-1

What about ?? Operator ? Yes, behind the scenes it's look similar, but in fact there is no any "if" statements.

Example of using:

var discount = _discountService.GetDiscountById(discountId) ?? throw new ArgumentException("Discount could not be loaded");
1
-1

You can do it by using ??(null-coalescing operator ) operator. Replace below code :

if (discount == null)
   throw new ArgumentException("Discount could not be loaded");

With

discount = discount??throw new ArgumentException("Discount could not be loaded");

Or you can use try catch block.

try
{
//main logic of methods continues here 
}    
catch(ArgumentNullException ex)
{
// handle exception
}
catch(Exception ex)
{
// handle exception
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.