Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# 7 - New Inline Out Variables

0.00/5 (No votes)
2 Oct 2017 1  
C# 7 has the ability to declare a variable right at the point where it is passed as an out argument

Introduction

In C# prior to version 7, to use an out variable, you must first declare a variable of the correct type, before actually using it, normally on the next line of code, as an out parameter, like:

var input = DateTime.Now.ToShortDateString();

DateTime start;
if (DateTime.TryParse(input, out start))
{
    // Do something with start.
}

This is really only trivially inconvenient, but the separation between the 'start' variable and the following code doesn't quite smell all roses.

Background

In C# 7, we now have what they call Inline Out Variables. In plain English, we can inline the declaration of an out variable in the same place it is used. This is a more cohesive approach without reliance on any external variable.

Using the Code

To use the out variables in the purer way, that is typed, you insert the type of the out variable immediately to the left of the variable name. This should place the type name right in front of the out keyword:

if (DateTime.TryParse(input, out DateTime start))
{
    // Do something with start.
}

We can also use implicitly typed variables as inline out variables:

if (DateTime.TryParse(input, out var start))
{
    // Do something with start.
}

Points of Interest

C# 7 is chock full of little but over some time, very, very handy improvements and even just shortcuts. I suggest if this interested you, have a look at the two artefacts: ref locals and returns. I'm quite certain I may even publish a tip here with them quite soon.

History

First time!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here