Out Parameter in c# 7.0

C# out parameter. 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. static void Main(string[] args)
  4. {
  5. string authorName, bookTitle;
  6. long publishedYear;
  7. GetAuthor(out authorName, out bookTitle, out publishedYear);
  8. Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",
  9. authorName, bookTitle, publishedYear);
  10. Console.ReadKey();
  11. }
  12. static void GetAuthor(out string name, out string title, out long year)
  13. {
  14. name = "praween Kumar";
  15. title = "A Programmer's Guide to .Net core with C#";
  16. year = 2020;
  17. }
  18. }

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. static void Main(string[] args)
  4. {
  5. AuthorByOutParam(out string authorName, out string bookTitle, out long publishedYear);
  6. Console.WriteLine("Author: {0}, Book: {1}, Year: {2}",
  7. authorName, bookTitle, publishedYear);
  8. Console.ReadKey();
  9. }
  10. static void AuthorByOutParam(out string name, out string title, out long year)
  11. {
    1. name = "praween Kumar";
    2. title = "A Programmer's Guide to .Net core with C#";
    3. year = 2020;
  12. }
  13. }


Recommended Free Ebook
Similar Articles