ref Keyword in c#

18.  ref Keyword in c#
C# supports built in data type value type and reference type. the value type variable is passed by value, and the reference type variable is passed by reference from one method to another method in C#.

Important point 


  1.  The ref keyword indicates that an argument is passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method
  2. You can declare the reference parameters using the ref keyword.
  3. A reference parameter is a reference to a memory location of a variable.
We have a method named GetData which takes an integer parameter. Inside the method, we will update this value. Then, we call this method and print the value of the parameter - before method call, inside the method, and after the execution of the method. So, the code will look like the following.

 class Program

    {     
        static void Main(string[] args)
        {
            int a = 4;
            Console.WriteLine("Value before method call is: " + a);
            GetData(a);      
            Console.WriteLine("Value after method call is: " + a);      
            Console.ReadLine();
        }
        public static void GetData(int a)
        {
            a = a + 990;
            Console.WriteLine("Value inside method is: " + a);
        }
    }
Output:
Value before method call is: 4
Value inside method is: 994
Value after method call is: 4

When we use ref key inside the method call.We have a method named GetData which takes an ref parameter inside the method.

 class Program

    {     
        static void Main(string[] args)
        {
            int a = 4;
            Console.WriteLine("Value before method call is: " + a);
            GetData(ref a);
            Console.WriteLine("Value after method call is: " + a);
            Console.ReadLine();
        }
        public static void GetData(ref int a)
        {
            a = a + 900;
            Console.WriteLine("Value inside method is: " + a);
        }
    }
see the difference between this output:-

Value before method call is: 4

Value inside method is: 904
Value after method call is: 904

hope you understand 'ref' keyword.