Parameter Modifiers in C#

In C++, we can pass by value, reference (pointers are also there) when we need to pass some data to a C++ function.

In the case of C# also we’ve the same facilities.(Pointers are still there). They’re named as ref, out and params.

Let’s take a look at ref keyword. As the name indicates, “ref” stands for reference. If the formal parameter (ref variable) modified inside the function, it will be also get reflected in the actually parameter. (Same as C++ reference). In C#, the object must be initialized before passing as a reference. The sytanx is clean in C# because we’re specifying the parameter modifier at both function definition and at the time of usage.


static void Foo(ref int nData)
{
	nData++;
}
static void Main(string[] args)
{
	int x = 10;
	Foo(ref x);
	int y;
	Foo(ref y); // ERROR: Uninitialized variables
}

Let’s take a look at out keyword. Out behaves similar to ref keyword but there’s no need to initialize the object passing to function. Even the object is initialized, inside the function, we’ve to re-initialize object. We can’t exclude this step.

In C++, there’s no constraint to use the reference variable inside the function. We can omit with/ without conditional statements. But in C# if you use out keyword, you will have to initialize the object inside the calling function. If you want the same behavior of C++ reference, it’s better to use ref keyword.

Ref and out keywords are same at the compilation time but behaves different at run time. So that you can’t overload “ref” and “out” with similar function signature.


static void Foo(ref Math m){}
static void Foo(out Math m){} // ERROR: can’t overload with ref and out keyword

params are allows to pass pass arbitrary number of parameters to this function. Params keyword has the following constraints. There should be only one params argument as function parameter and it should be appeared as the last parameter of a function(or no other parameters can be passed after a param variable)
See the same sample from MSDN


using System;
public class MyClass
{
	public static void UseParams(paramsparams int[] list)
	{
		for (int i = 0 ; i < list.Length; i++)
		{
			Console.WriteLine(list[i]);
		}
		Console.WriteLine();
	}

	public static void UseParams2(params object[] list)
	{
		for (int i = 0 ; i < list.Length; i++)
		{
			Console.WriteLine(list[i]);
		}
		Console.WriteLine();
	}

	static void Main()
	{
		UseParams(1, 2, 3);
		UseParams2(1, 'a', "test");

		// An array of objects can also be passed, as long as
		// the array type matches the method being called.
		int[] myarray = new int[3] {10,11,12};
		UseParams(myarray);
	}
}

Respond to this post