Back
Close

Out-variables in C#

gpeipman
14.7K views

Out-variables in C#

C# 7.0 brings some features to out-variables. These new features help us write cleaner code and handle out-variables better.

Let's start with simple piece of code where out-variable is used.

Inline out-variables

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

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

Using var

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

Skipping out-variable

Sometimes we don’t need out variable at all. Good example is removing elements from concurrent dictionary. For this we use underscore (_) as variable name.

References

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants