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.
- 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 = "praween Kumar";
- title = "A Programmer's Guide to .Net core with C#";
- year = 2020;
- }
-
- }
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.
- 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 = "praween Kumar";
- title = "A Programmer's Guide to .Net core with C#";
- year = 2020;
-
- }
-
- }