Out Variables In C# 7.0

Prior to 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.

  1. class Program    
  2. {  
  3.   
  4. static void Main(string[] args)    
  5. {    
  6.   string authorName, bookTitle;    
  7.   long publishedYear;    
  8.   GetAuthor(out authorName, out bookTitle, out publishedYear);    
  9.   Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",    
  10.   authorName, bookTitle, publishedYear);    
  11.   Console.ReadKey();    
  12. }  
  13.   
  14. static void GetAuthor(out string name, out string title, out long year)   
  15. {    
  16.   name = "Mahesh Chand";    
  17.   title = "A Programmer's Guide to ADO.NET with C#";    
  18.   year = 2001;    
  19. }  
  20.   
  21. }  

Listing 1

If we try to declare the type of these out parameters in the method, the compiler gives an error.

In C# 7.0, now it is possible.

Now, you can define a method's out parameters directly in the method. The new code looks like Listing 2.

  1. class Program  
  2. {  
  3.   
  4. static void Main(string[] args)  
  5. {  
  6.   AuthorByOutParam(out string authorName, out string bookTitle, out long publishedYear);  
  7.   Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",  
  8.   authorName, bookTitle, publishedYear);  
  9.   Console.ReadKey();  
  10. }  
  11.   
  12. static void AuthorByOutParam(out string name, out string title, out long year)  
  13. {  
  14.   name = "Mahesh Chand";  
  15.   title = "A Programmer's Guide to ADO.NET with C#";  
  16.   year = 2001;  
  17. }  
  18.   
  19. }  
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 publishedYear parameter, you could just replace it with an ‘*’.

  1. AuthorByOutParam(out string authorName, out string bookTitle, out *);  

Summary

This article talks about some of the new changes introduced in C# 7.0 regarding out 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/

Up Next
    Ebook Download
    View all
    Learn
    View all