Condition optimization

Asked

Viewed 71 times

3

A comparison is possible (if 1 or equal to null) simpler than the one made in my code?

@((Model.Visibilidade == 1 || Model.Visibilidade == null) ? "checked" : "")
  • the Visibilidade is a int? thus?

  • That’s right, it’s a int?

1 answer

4


Can’t.

I would do so:

@((Model.Visibilidade == null || Model.Visibilidade == 1) ? "checked" : "")

I put in the Github for future reference.

In this case there is no problem because it is a int?, but in cases of types by reference would give error. If it is null and try to make the comparison with a value will give error, then it is correct to buy the null first. To maintain consistency I would always do in this order, even if in this case I can compare the value first.

  • Really the order is reversed, it should give error, but it did not. Yes it is a int?

  • It didn’t work because the valoe is 1, if it was null would make a mistake.

  • No, the value really is null, the code is in an inclusion/change dialog, where there is no default value for the record Model.Visibilidade

  • This is a mistake Model.Visibilidade === 1

  • C# does not have ===. In fact it’s no mistake, I didn’t remember this behavior of int?, and it even makes sense. I updated the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.