L0laapk3
L0laapk3

Reputation: 958

Double if else without brackets

I recently discovered that you can use the following syntax for if/else statements:

if (a)
    b = true;
else
    b = false;

when you nest another if clause inside this, it gets confusing

if (a)
    if (b)
         c = 3;
else
    c = 1;

but since the compiler ignores line indents, the compiler always parses this as (from what I understand)

if (a)
    if (b)
         c = 3;
    else
         c = 1;

Is it possible to achieve the second clause without using brackets? (I am aware that this makes no difference, but it is cleaner in my opinion)


EDIT: For all the comments suggesting something along the lines of the following:

if (a && b)
    c = 3;
else
    c = 1;

This is not the same. if a = true and b = false, c will be set to 1, but the expected value is that it wouldn't be set at all.

Upvotes: 1

Views: 1513

Answers (4)

e.roche
e.roche

Reputation: 156

If you have mutli-lines condition you must put braces. C# don't care about indentation like Python..

if(condition)
//enter if statement
//leave if statement

Upvotes: 1

user1666620
user1666620

Reputation: 4808

You could use a ternary, but if the logic is complex it could get ugly/hard to read.

c = a ? (b ? 3 : 1) : c;

if a is false the value of c will not change.

You could remove the brackets, but nested ternaries are hard to read and I would suggest they are an antipattern.

Upvotes: 0

David van Rensburg
David van Rensburg

Reputation: 1

if (a && b)
     c = 3;
else if (a && !b)
     c = 1;

This will do exactly what you want. But one of the reasons for having brackets is to avoid confusion like this. Adding the bracket will make it much easier to read.

Upvotes: 0

Luaan
Luaan

Reputation: 63752

Well, if you want to bring over your own language into C#, why not in style? Define an If method!

public static void If(Func<bool> condition, Action ifTrue, Action ifFalse = null)
{
  if (condition()) ifTrue(); else if (ifFalse != null) ifFalse();
}

Then you can represent your code with

var a = false;
var b = true;
var c = 0;

If(() => a, () => If(() => b, () => c = 3), () => c = 1);

Bang - no braces! You don't even have to indent :-P Don't worry if someone suggests that this is hard to read - after all, why would you have to accomodate other programmers; if worst comes to worst, just recruit your C#ers from old LISPers[1], and noöne will bat an eye at this ;)

Disclaimer:

Don't.

[1] - No offense meant to LISP or LISPers.

Upvotes: 2

Related Questions