Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

C# 7.0: Out Variables

DZone's Guide to

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!

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

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.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:
variables ,c# ,web dev

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}