Understanding ref, out and params keyword in C#

Nov 21, 2011

I would start this.life and connect with the world by explaining three important C# keywords – ref, out and params also known as “Method parameter keywords”.

These keywords are called method parameter keywords because they are used to change the behaviour of parameters passed into any method.

C# Keyword - params

This parameter keyword can be used to specify method parameter that takes variable number of arguments. When the number of values required are not fixed and the internal mechanism can handle variable number of arguments processing, in that situation we can use params keyword for a method parameter. This method parameter can either accept comma-separated list of arguments of specified type, array of arguments of specified type or no arguments.

    public void DemonstrateParams(params int[] inputParamList)
    {
        if (inputParamList.Length >= 1)
        {
            for (int counter = 0; counter > inputParamList.Length; counter++)
            {
                Console.WriteLine("Parameter No:" 
                + counter + " = " + inputParamList[counter]);
            }
        }
        else
        {
            Console.WriteLine("No parameter found !!");
        }
    }

Above code snippet demonstrates the use of params keyword for method parameter of type int. So we can call the above method with an array list of values.

paramsKeywordObj.DemonstrateParams (1,2,3,4);

or

int[] inputParameterList = { 0, 1, 2, 3, 4, 5 };
paramsKeywordObj.DemonstrateParams (inputParameterList);

We can also call the method without passing any parameter value like:

paramsKeywordObj.DemonstrateParams ();

If we change the method parameter type from int to object we can have variable numbers of reference object that can be passed to the method using params.

Method signature:

public void DemonstrateParams(params object[] inputParamList)
paramsKeywordObj.DemonstrateParams (null);

Here if we pass null to the method, then null will not be the first element of the object[] array, but it will be null inputParamList object[] array.
Good coding practice is to check for null value before using the method parameter having params keyword specified.

Remember

  • After the method parameter with params keyword, no other parameters can be specified.
  • There can only be one method parameter with params keyword.

C# Keyword - ref

A normal method parameter is passed by value (Note: Do not get this confused by passing reference type and value type). But using ref keyword we can pass an argument by reference.

This means that when value of that parameter is changed in the method, it gets reflected in the calling environment (caller method).  This keyword can be used by specify ref in method definition and at the calling method explicitly.

Method definition:

public void DemonstrateRef(ref int inputParam)
{
	Console.WriteLine("Value of ref Parameter is : " + inputParam);
}

Call to the method:

int somevalue = 10;
refKeywordObj = new RefKeyword();
refKeywordObj.DemonstrateRef(ref somevalue);

Another example demonstrating passing a reference type using ref keyword

Definition of Reference type:

class SomeReferenceType
{
     public SomeReferenceType(string someString)
     {
          SomeString = someString;
     }

     public string SomeString { get; set; }
}

Method definition:

public void DemonstrateRef(ref SomeReferenceType inputParam)
{
     Console.WriteLine
     ("Value of SomeString before any change to reference type : "
     + inputParam.SomeString);

     //// Change in value of SomeString 
     //// is also reflected in the Calling enviroment.
     inputParam.SomeString = "Value Changed";
     Console.WriteLine
     ("Value of SomeString after changed : "
     + inputParam.SomeString);

     //// Can change the value address 
     //// stored in the parameter by reinitializing the object.
     //// Thus new reference address is stored 
     //// at the Calling environment also.
     inputParam = new SomeReferenceType("New value");
     Console.WriteLine
     ("Value of SomeString after reinitialization : "
     + inputParam.SomeString);
}

Call to the method:

SomeReferenceType someReferenceVariable = new SomeReferenceType("Old Value");
refKeywordObj.DemonstrateRef(ref someReferenceVariable);

Thus the reference address change or any change to the reference type is done to the original reference value and is reflected at the calling environment end.

To Remember

  • An argument that is passed using a ref keyword must be initialized before it is passed.
  • Properties cannot be passed to ref parameters. Internally they are functions and not members / variables.

C# Keyword - out

Keyword out can be used in two different contexts:
1). Parameter modifier
2). In generic type parameter declarations in interface and delegates.

Keyword out also causes argument to be passed by reference like ref keyword, but argument with out keyword can be passed with initialization of the variable or without assigning any value to it. This keyword can be used by specifying out at method definition and at the calling method explicitly.

Method definition:

public void DemonstrateOut(out int someValue)
{
     // Assign some value before method returns.
     someValue = 10;
}

Call to method:

int outValue;
keywordOutObj.Method(out outValue);

To Remember

  • An argument that is passed using an out keyword must be initialized in the method before it return and from all code paths.
  • Properties cannot be passed to out parameters. Internally they are functions and not members / variables.

Similarity between ref and out keyword in C#

  • Both can be used to return multiple values from any method. But out keyword can be used to return multiple values optionally.
  • The method parameter with ref and out keyword behaves same at compile time and is considered same. Thus, methods cannot be overloaded if the only difference is that one method takes ref argument and other takes out argument.

Difference between ref and out keyword in C#

  • ref parameter must be initialized before calling the method. out parameter must be initialized in the method and from all code paths before it returns.
  • Reading an out argument in the method before it is initialized or assigned is not allowed. Whereas ref argument can be read anytime once it's value is assigned or initialized before call to the method.
  • Information cannot be passed into the method when out argument is specified as it has to be initialized in the method before using. On the other hand ref argument can be used to pass information or value to the method and get some value in the same variable back at the calling environment.

Let us Summarize

Keyword ref, out and params are also called "Method parameter keywords". Keyword params can be used when the number of argument are variant or none. Keyword ref and out can be used to return multiple values with different behaviors.