Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c# - ?: ?? Operators Instead Of IF|ELSE

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...