What are the advantages of discards in c#

后端 未结 3 790
滥情空心
滥情空心 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:41

    I believe this deals more with initial memory allocation rather than JUST memory management. So if you do not consume the output variable then it is still going to pushed onto the stack regardless if it is a ref type. (Yeah so the val types in your question won't be and I see your point there.) but if you are dealing with something like a filestream and didn't close the stream then I believe you are going to be holding onto that for the application lifecycle. That said then you have to be conscious of anything implementing IDisposable. I would think that discards could have a relatively bigger impact in that regard.

    Past that, dealing with out params passed into functions, it prevents the initial memory allocation of those variables since you won't be using them. It may not have a huge impact on smaller projects but if you have some method that is used excessively across an application then it's use is more applicable than just some new trendy style.

提交回复
热议问题