Software & Finance





C# - Reference Variables - ref and out





ref is similar to have the reference variable in C++. ref variable in sub function meaning that the value can not be null and must be assigned and it should be passed with ref keyword. out is similar to ref except that the value must be assigned before the sub function returns the call.

 

d.ChangeValue(ref a, out b);

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Basics

{

    class Sample

    {

 

        public void ChangeValue(ref int p, out int q)

        {

            p = 15;

            // Commenting the following line will produce compile time error

            // error CS0177: The out parameter 'q' must be assigned to 

            // before control leaves the current method

            q = 25;

        }

 

        public void ChangeValue(int p, int q)

        {

            p = -1;

            q = -1;

        }

 

        static void Main(string[] args)

        {

            Sample d = new Sample();

 

            int a = 10;

            int b = -1;

 

            Console.WriteLine(a);

            Console.WriteLine(b);

            Console.WriteLine();

 

            // Use of ref and out keywords

            d.ChangeValue(ref a, out b);

            Console.WriteLine(a);

            Console.WriteLine(b);

            Console.WriteLine();

           

            // Use of ref and out keywords

            d.ChangeValue(a, b);

            Console.WriteLine(a);

            Console.WriteLine(b);

            Console.WriteLine();

        }

    }

}

Output


 

10

-1

 

15

25

 

15

25