C# out and ref keywords

In C# we can pass a variable to a function by address, which means, instead of passing value of a variable, we can pass its address. To do so, we can use out, and ref keywords.

The different between ref and out is that, the variable passed with ref keyword must be initialized before passing its reference, where variable initialization is not mandatory in case of out keyword. The following is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{   
    class Program
    {
   
        static void Main(string[] args)
        {
            int num1 = 10;
            int num2;

            Console.WriteLine(num1);
            GetRefValue(ref num1);
            Console.WriteLine(num1);
            
            GetOutValue(out num2);
            Console.WriteLine(num2);
        }

        static void GetRefValue(ref int num1)
        {
            num1 = 100;
        }

        static void GetOutValue(out int num2)
        {
            num2 = 100;
        }
    }
}

 

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *