What are the advantages of discards in c#

后端 未结 3 939
滥情空心
滥情空心 2021-01-13 03:25

I\'ve just come across discards in c# and am wondering a couple things that I feel Microsoft Docs on Discards didn\'t explain very well.

  1. With a standalone disc
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 03:57

    In general, there is no sense to use discard in this sentence:

    _ = nc.Read(someBuffer, 0, someSize);
    

    since you can just ignore the return value. I did never anyone using standalone discards, but the documentation covers some specific cases when it can be useful.

    The discards are used when you have to provide a variable, but don't need it.
    As already covered in the provided documentation page, discards are very useful for:

    Pattern matching

    switch (stream)
    {
        case MemoryStream _:
        case FileStream _:
            ProcessStream(stream);
            break;
    }
    

    Methods with out parameters

    If you want to check if you can parse a string to an integer, but don't care about the result:

    if (int.TryParse(str, out _))
    {
        // do something
    }
    

    Otherwise, you would have to declare an out variable, which you wouldn't use and which would consume some memory.

    Deconstruction

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

    Without discards you would deconstruct the result into 3 different variables, and use only one of them. With discards the code has cleaner intentions and more ineffective in terms of memory management.

提交回复
热议问题