C#7: Underscore ( _ ) & Star ( * ) in Out variable

后端 未结 6 625
情书的邮戳
情书的邮戳 2020-11-27 17:08

I was reading about new out variable features in C#7 here. I have two questions:

  1. It says

    We allow \"discards\" as out parameters as w

6条回答
  •  庸人自扰
    2020-11-27 17:19

    In C# 7.0 (Visual Studio 2017 around March 2017), discards are supported in assignments in the following contexts:

    • Tuple and object deconstruction.
    • Pattern matching with is and switch.
    • Calls to methods with out parameters.
    • A standalone _ when no _ is in scope.

    Other useful notes

    • discards can reduce memory allocations. Because they make the intent of your code clear, they enhance its readability and maintainability
    • Note that _ is also a valid identifier. When used outside of a supported context

    Simple example : here we do not want to use the 1st and 2nd params and only need the 3rd param

    (_, _, area) = city.GetCityInformation(cityName);
    

    Advanced example in switch case which used also modern switch case pattern matching (source)

    switch (exception)                {
    case ExceptionCustom exceptionCustom:       
            //do something unique
            //...
        break;
    case OperationCanceledException _:
        //do something else here and we can also cast it 
        //...
        break;
    default:
        logger?.Error(exception.Message, exception);
        //..
        break;
    

    }

提交回复
热议问题