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))
{
}
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))
{
}
We can also use implicitly typed variables as inline out
variables:
if (DateTime.TryParse(input, out var 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!