0

I have a scenario where a form containing a checkbox is submitted, being its element name "someFlag".

If checked, it will come as "on".

If not checked, it will come as empty.

So I'm checking the emptyness of the someFlag string and assigning the value 1 if it is on and the value 0 if it is empty.

It works fine but, can this

if (String.IsNullOrEmpty(someFlag))
    someFlag= "0";
else
    someFlag= "1";

be written in a shorter way?

EDIT

This isn't a duplicate of this question as I'm asking for a solution for a specific scenario, not a broad opinion based question such as the mentioned (it has been closed for that reason). I'm asking a question with two possible answers: yes or no.

Community
  • 1
  • 1
chiapa
  • 4,362
  • 11
  • 66
  • 106
  • If you were just checking for null, you could use coalesce: `someFlag = someFlag ?? "1";` – Mathew Thompson May 07 '15 at 14:59
  • Shorter code is not always better code, prefer readability over one liners. – DGibbs May 07 '15 at 14:59
  • possible duplicate of [To ternary or not to ternary?](http://stackoverflow.com/questions/160218/to-ternary-or-not-to-ternary) – Bob G May 07 '15 at 15:00
  • @DGibbs, that's an interesting point. Could you check [this question](http://stackoverflow.com/questions/30073895/readability-vs-performance-comparison) please? – chiapa May 07 '15 at 15:19

1 Answers1

4

You can use the ternary operator

someFlag = String.IsNullOrEmpty(someFlag) ? "0" : "1"

but I don't think you can shorten it further.

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 1
    it is called the [conditional operator](https://msdn.microsoft.com/en-us/library/e4213hs1.aspx) (although it **is** a ternary operator) – default May 07 '15 at 15:00
  • @Default I didn't even know... I had always called it the ternary operator, and I hadn't ever thought that it isn't technically *the only possible* ternary operator (while at the same time, in programming, it *is* *The* ternary operator) – xanatos May 07 '15 at 15:03