DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

C# 7.0: Out Variables

C# 7.0 handles out variables a bit differently, bringing some new features to the table. Read on to find out more about what's in store!

Gunnar Peipman user avatar by
Gunnar Peipman
·
Mar. 24, 17 · Tutorial
Like (2)
Save
Tweet
Share
4.84K Views

Join the DZone community and get the full member experience.

Join For Free

C# 7.0 brings some features to out variables. These new features help us write cleaner code and handle out variables better. This blog post provides samples of these new features in C# 7.0 and as a surprise, it also demonstrates what the compiler is doing with these new features.

Inline out Variables

Let’s start with a piece of code that demonstrates how TryParse() and some TrySomethingElse() methods work.


var intString = "1111";
int i = 0;

if(int.TryParse(intString, out i))
{
    // it's integer
}
else
{
    // it's not integer
}

The code above uses out variable i that needs to be declared before TryParse() method is called. In the case of a method with more out variables, we have to declare all these variables before calling the method. Imagine three out variables of a different type, for example.

C# 7.0 allows us to define out variables inline. The previous code can be written this way.


var intString = "1111";

if(int.TryParse(intString, out int i))
{
    // it's integer
}
else
{
    // it's not integer
}

NB! Use this trick if you are using out variables near where they are defined. If you also need this variable in other blocks that follow the declaring block then better go with a traditional out variable.

Using var

But we don’t have to specify the type of out variable directly. The compiler can find it for us, and this means we can also go with var. The next piece of code is the same as the previous one.


var intString = "1111";

if(int.TryParse(intString, out var i))
{
    // it's integer
}
else
{
    // it's not integer
}

NB! Here we lose nothing when using var as it is easy to see that the out type will be int. For other methods with out variables, like those you can find when using P/Invoke, we need an actual type to be written out if the same line doesn’t communicate it clearly.

Skipping the out Variable

Sometimes we don’t need an out variable at all. A good example is removing elements from a concurrent dictionary. Here is the fragment of code from my ASP.NET Core WebSocket chat room example. In the WebSocket middleware class, I have to remove the instance of socket from concurrent dictionary _sockets.


WebSocket dummy;
_sockets.TryRemove(socketId, out dummy);

await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
currentSocket.Dispose();

When removing the socket I’m not interested in getting the instance of it because I already have it. On C# 7.0 we can skip the out variable by replacing it with an underscore.


_sockets.TryRemove(socketId, out _);

NB! ConcurrectDictionary<T,U> has TryRemove() method like this for certain reasons and it is not a design flaw.

Using out variable skipping, we can easily write code to check if the string value can be turned to an integer or not.


if(int.TryParse(intString, out _))
{
    // it's integer
}

Behind the Compiler

Let’s take a look at what the compiler actually produces if we build a method that uses out variable skipping. Here is the method:


static void Main(string[] args)
{
    var intString = "1111";if(int.TryParse(intString, out _))
    {
        // it's integer
    }
    else
    {
        // it's not integer
    }       Console.ReadLine();
}

Now let’s build the program and open the resulting DLL in JetBrains dotPeek.


private static void Main(string[] args)
{
    int result;
    if (!int.TryParse("1111", out result))
        ;
    Console.ReadLine();
}

We get straight back to the roots.

Wrapping Up

Out variables that are used in the same block with TrySomething() method can now be declared inline where these variables are used in the method call. Also, the keyword var is supported. Inline declarations of out variables lead us to cleaner code, but we may lose readability if these out variables are also used in other code blocks. Out variable skipping is a good option when we don’t care about the value of our out variable. Like with everything else in coding, there is one suggestion: use these features carefully and only if you benefit from them.

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • Key Elements of Site Reliability Engineering (SRE)
  • Benefits and Challenges of Multi-Cloud Integration

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: