C# out parameter. Before C# 7.0, the out keyword was used to pass a method argument's reference. Before a variable is passed as an out argument, it must be declared. However, unlike the ref argument, the out parameter doesn’t have to be initialized.
To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
The code snippet in Listing 1 defines the GetAuthor method with three out parameters.
class Program
{
static void Main(string[] args)
{
string authorName, bookTitle;
long publishedYear;
GetAuthor(out authorName, out bookTitle, out publishedYear);
Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",
authorName, bookTitle, publishedYear);
Console.ReadKey();
}
static void GetAuthor(out string name, out string title, out long year)
{
name = "Mahesh Chand";
title = "A Programmer's Guide to ADO.NET with C#";
year = 2001;
}
}
Listing 1
If we try to declare the type of these parameters in the method, the compiler gives an error.
In C# 7.0, now it is possible
Now, you can define a method's parameters directly in the method. The new code looks like Listing 2.
class Program
{
static void Main(string[] args)
{
AuthorByOutParam(out string authorName, out string bookTitle, out long publishedYear);
Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",
authorName, bookTitle, publishedYear);
Console.ReadKey();
}
static void AuthorByOutParam(out string name, out string title, out long year)
{
name = "Mahesh Chand";
title = "A Programmer's Guide to ADO.NET with C#";
year = 2001;
}
}
Listing 2
Wildcards out variable
According to Mads Torgersen, Microsoft plans to include a wildcards ‘*’ symbol as a parameter name if you want to ignore an out parameter of a method. It is, however, not certain if this feature will be a part of C# 7.0. For example, in the above code snippet, if you don’t care about the published year parameter, you could just replace it with an ‘*’.
AuthorByOutParam(out string authorName, out string bookTitle, out *);
Summary
This article talks about some of the new changes introduced in C# 7.0 regarding our variables.
Next C# 7.0 Feature >> Ref Returns In C# 7.0
References
References used to write this article.
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/