Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of using ternary operator

Tags:

c#-4.0

I have the following statments in my source code

int tableField1;
int tableField2;

int propertyField1;
int propertyField2;

if (tableField1 != null)
{
  propertyField1 = tableField1;
}

if (tableField2 != null)
{
  propertyField2 = tableField1;
}

// the above pattern is repeated for 10 tablefields ie tableField3, tableField4... tableField10

I reduced the above statments using the ternary operator as follows

propertyField1 = tableField1 != null ? tableField1 : propertyField1;
propertyField2 = tableField2 != null ? tableField2 : propertyField2;

Following are my questions:

1) Is ternary operator inefficient to use than the if statements.

2) What are the disadvantages (if any) to use ternary operator.

like image 476
pradeeptp Avatar asked Dec 09 '22 12:12

pradeeptp


1 Answers

Why not use the null coalescing operator instead?

propertyField1 = tableField1 ?? propertyField1;

Admittedly it looks slightly odd assigning the original value back to the same variable. It's possible that it'll be very slightly less efficient than the if statements, as in theory you're reading the value and assigning it again... but I wouldn't be surprised if the JIT elided that. Anyway, that's definitely at the level of micro-optimization.

Some people consider the conditional operator to be bad for readability - I generally think it's fine for simple statements like this, although it is somewhat obscuring the meaning of "only change the value if we've got a new one".

like image 67
Jon Skeet Avatar answered Feb 23 '23 00:02

Jon Skeet