Difference Between Ref And Out In C#

Ref:

  • The ref keyword is used in C# for transmitting or receiving references of values to or from methods. It basically means that any modification made to a value that is transferred by reference will reflect this change as you are changing the value at the address and not just the value.

Example:

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 12;
            Add(out a);
            Console.WriteLine("The addition value is: {0}", a);
        }

        public static void Add(out int a)
        {
            a = 30;
            a += a;
        }

    }
}

out:

  • You can supply arguments of the out-type in C# by using the out keyword. It is comparable to the reference type, with the exception that initialising the variable prior to passing is not required. We must utilise the out keyword in order to pass an argument as an out-type. It is useful when we want a function to return a range of values.

Example:

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 12;
            subtract(ref b);
            Console.WriteLine("The subtraction value is: {0}", b);
        }

        public static void subtract(ref int b)
        {
            b -= 5;
        }
    }
}

Output:

Submit a Comment

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

Subscribe

Select Categories