Code Mahek
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot

Fragrance
​of Programming

Discards in C# 7.0

9/15/2017

Comments

 
We all might have encountered in which sometimes we need to ignore the returned values, especially the "out" arguments, and the best example is the TryParse method in which we check whether the string can be parsed to another type.

In the aboe co​de I want to ignore "boolParsedValue" and also want to make this variable inaccessible for developers so that they can reference it. With new C# 7.0, you can achieve this goal using "discards"
​Discards
​Discards are write-only local variable, in which you can assign but cannot read. They don't have names but are represented by "_ (underscore)". Since _ cannot be read, it will not appear on the right side of an assignment. Discard in the above code will be as below.

Because _ is not readable, it will not appear in IntelliSense nor will compile the code.
​Now suppose in the  above code you explicitly define the _ variable and assign the value true, in that case _ will be not considered as discard since you are explicitly declaring the _ local variable.

Interesting trick

Value of v in the above code false, if you see properly in the check condition we have written out var _, and it will overrides the scope of previously declared _ variable. Assignment v = _ just reads the previously declared local variable (false) and assigns to v.
Comments
comments powered by Disqus

    RSS Feed

    Categories

    All
    Azure
    C#
    Cloud
    CodeProject
    CSharp
    DotNet Core
    Jetbrains
    .NET
    Rider
    Source Generators
    SQL
    Tech News
    Ubuntu
    Visual Studio 2015
    Visual Studio 2019
    Windows
    Windows 10

    Archives

    May 2020
    February 2019
    January 2019
    December 2018
    May 2018
    December 2017
    November 2017
    October 2017
    September 2017
    July 2017
    May 2017
    April 2017
    May 2015
    April 2015
    March 2015

    View my profile on LinkedIn

Location

Contact Us

    Subscribe Today!

Submit
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot