public string Source { get { /* if ( Source == null ){ return string . Empty; } else { return Source; } */ return Source ?? string.Empty; } set { /* if ( Source == null ) { Source = string . Empty; } else { if ( Source == value ) { Source = Source; } else { Source = value; } } */ Source == value ? Source : value ?? string.Empty; RaisePropertyChanged ( "Source" ); } }
Can I use ?:
??
operators EXACTLY as If/Else?
My Question :
How to write the following with ?: ?? operators
[ 1 ]
if ( Source == null ){ // Return Nothing } else { return Source; }
[ 2 ]
if ( Source == value ){ // Do Nothing } else { Source = value; RaisePropertyChanged ( "Source" ); }
Briefly : How to do nothing, return nothing and do multiple instructions with ?:
??
operator?
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
The ternary conditional operator ?: allows us to define expressions in Java. It's a condensed form of the if-else statement that also returns a value.
The conditional operator (? :) is a ternary operator (it takes three operands).
For [1], you can't: these operators are made to return a value, not perform operations.
The expression
a ? b : c
evaluates to b
if a
is true and evaluates to c
if a
is false.
The expression
b ?? c
evaluates to b
if b
is not null and evaluates to c
if b
is null.
If you write
return a ? b : c;
or
return b ?? c;
they will always return something.
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
The ternary operator (?:
) is not designed for control flow, it's only designed for conditional assignment. If you need to control the flow of your program, use a control structure, such as if
/else
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With