?: ?? Operators Instead Of IF|ELSE

前端 未结 9 1617
粉色の甜心
粉色の甜心 2020-11-28 02:09
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
                


        
相关标签:
9条回答
  • 2020-11-28 02:55

    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 ...

    0 讨论(0)
  • 2020-11-28 02:55

    The ternary operator RETURNS one of two values. Or, it can execute one of two statements based on its condition, but that's generally not a good idea, as it can lead to unintended side-effects.

    bar ? () : baz();
    

    In this case, the () does nothing, while baz does something. But you've only made the code less clear. I'd go for more verbose code that's clearer and easier to maintain.

    Further, this makes little sense at all:

    var foo = bar ? () : baz();
    

    since () has no return type (it's void) and baz has a return type that's unknown at the point of call in this sample. If they don't agree, the compiler will complain, and loudly.

    0 讨论(0)
  • 2020-11-28 03:01

    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.

    0 讨论(0)
提交回复
热议问题