?: ?? Operators Instead Of IF|ELSE

Ahmed Ghoneim picture Ahmed Ghoneim · Jun 1, 2011 · Viewed 249.9k times · Source
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?

Answer

trutheality picture trutheality · Jun 1, 2011

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.