Out-variables in C#

gpeipman
1,501 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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.

Click Run to see the demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
·using System;
namespace ClassicExample
{
class Program
{
static void Main(string[] args)
{
var intString = "1111";
int i = 0;
if (int.TryParse(intString, out i))
{
Console.WriteLine(intString + " is integer");
}
else
{
Console.WriteLine(intString + " is not integer");
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

Click Run to see the demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
·using System;
namespace InlineExample
{
class Program
{
static void Main(string[] args)
{
var intString = "1111";
if (int.TryParse(intString, out int i))
{
Console.WriteLine(intString + " is integer");
}
else
{
Console.WriteLine(intString + " is not integer");
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

Click Run to see the demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
·using System;
namespace VarExample
{
class Program
{
static void Main(string[] args)
{
var intString = "1111";
if (int.TryParse(intString, out var i))
{
Console.WriteLine(intString + " is integer");
}
else
{
Console.WriteLine(intString + " is not integer");
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

Click Run to see the demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
·using System;
namespace SkipOutVarExample
{
class Program
{
static void Main(string[] args)
{
var intString = "1111";
if (int.TryParse(intString, out _))
{
Console.WriteLine(intString + " is integer");
}
else
{
Console.WriteLine(intString + " is not integer");
}
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content