?: ?? Operators Instead Of IF|ELSE
Solution 1:
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
.
Solution 2:
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
.
Solution 3:
Refering to ?: Operator (C# Reference)
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
Refering to ?? Operator (C# Reference)
The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
That means:
[Part 1]
return source ?? String.Empty;
[Part 2] is not applicable ...
Solution 4:
The "do nothing" doesn't really work for ?
if by // Return Nothing you actually mean return null then write
return Source;
if you mean, ignore the codepath then write
if ( Source != null )
{
return Source;
}
// source is null so continue on.
And for the last
if ( Source != value )
{ Source = value;
RaisePropertyChanged ( "Source" );
}
// nothing done.