Out And Ref Parameters In C#

Introduction

The out and the ref parameters are used to return values in the same variables that you pass as an argument of a method. These parameters are very useful when your method needs to return more than one value.

In this article, I will explain how to use these parameters in your C# applications.

The out Parameter

The out parameter can be used to return the value in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

public class MathClass
{
    public static int TestOut(out int iVal1, out int iVal2)
    {
        iVal1 = 10;
        iVal2 = 20;
        return 0;
    }
}
public static void Main()
{
    int i, j;   // variables need not be initialized
    Console.WriteLine(MathClass.TestOut(out i, out j));
    Console.WriteLine(i);
    Console.WriteLine(j);
}

The ref parameter

The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.

You can even use ref for multiple method parameters.

static void Main(string[] args)
{
    // Ref sample
    int refi; // variable need not be initialized
    refi = 3;
    RefTest(ref refi);
    Console.WriteLine(refi);
    Console.ReadKey();
}
public static void RefTest(ref int iVal1)
{
    iVal1 += 2;
}

Complete sample

using System;
namespace RefOutSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Out sample
            int i, j;   // variable need not be initialized
            Console.WriteLine(TestOut(out i, out j));
            Console.WriteLine(i);
            Console.WriteLine(j);
            // Ref sample
            int refi; // variable need not be initialized
            refi = 3;
            RefTest(ref refi);
            Console.WriteLine(refi);
            Console.ReadKey();
        }
        public static int TestOut(out int iVal1, out int iVal2)
        {
            iVal1 = 10;
            iVal2 = 20;
            return 0;
        }
        public static void RefTest(ref int iVal1)
        {
            iVal1 += 2;
        }
    }
}


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.