ref and out keyword in c#

Out keyword in C#

If you want to return multiple outputs from a function you will use the OUT keyword.

In Out key, When we passed variables as out arguments that time we initialized the variables within the methods. It is also known as the output parameter.

Ref keyword is a one-way communication while the out keyword is two-way communication.
  1. Initialized must be inside the methods. 
  2. Before calling the methods may be initialized or not initialized the values of the variables.
A simple code sample is given below


public class OutClass
{
    static void Method(int a, int b, out int add)
    {
        add = a+b;
    }
    static void Main()
    {
        int add=0;
        Method(10, 10, out add);
    }
}

Some important notes as given below

  1. The ref and out keywords are treated differently at run-time but they are treated the same at compile time. 
  2. Methods cannot be overloaded if one method takes a ref keyword and the other takes an out keyword.

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Out keyword in C# Out keyword in C# Reviewed by Anil Singh on 3:08 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^