Nullable bool or bool with default value in action?

Perhaps a small question, but they are curious.

What do you like?

In the action of controllers when passing arguments, when and how to use them?

public ActionResult Action(bool aBool = false) 

or

 public ActionResult Action(bool? aNullableBool) 

I tend to use defualt-value as its a little clearer and easier to check, but am I thinking wrong?

+4
source share
4 answers

These two are not equivalent. In the first example, the caller must indicate true or false ; if he does not, false used.

In the second line, the caller can provide true or false or null . You will need to decide how to handle null . This is the third value you can get. In addition, the caller cannot omit it. He needs to convey the meaning.

+5
source

The .HasValue property of values ​​with zero values ​​can be quite useful sometimes. Having a nullable bool is similar to having a bool in a bool. Take the Chuong Les database example , when you read a cell, you can check if the cell really matters before continuing (and ends with an error further down the line).

Instead of making sure this is not the case, before reading the cell you can use a variable with a null value and use if (aNullableBool.HasValue) to make sure you have a value before continuing.

As you said, if you are not at risk of getting a variable that gets null , you should use the default value.

+2
source

I think the default value in the route configuration will be better.

0
source

It depends on the role of your bool.

If you want to have a default value or not (default behavior + just one other behavior), so there are only 2 behaviors of this method.

If you want to have the third behavior as the default behavior, you need to use a nullable bool.

So, think about the needs of your method and choose accordingly.

0
source

Source: https://habr.com/ru/post/1480894/


All Articles