Parameters Introduction
As we know that C# is an object oriented programming language and being object oriented means that the users of the objects need to interact with the data members of the objects and this can be achieved by using the member functions of the class. Passing parameters to the member functions or the static functions of the class is important part of programming, that is why it is very important to understand the ways in which we can pass the parameters to the functions in C#.
CodeProject
Before starting the article you may want to know about value types and reference types in C# which I have discussed in my one of my articles.
There are basically two ways in which we can pass parameters to the functions in C#.
- Pass by Value
- Pass by reference.
I want to discuss both of these ways here one by one
- Pass By Value-
Passing value types by Value – By default all the parameters are passed by value.For value type a copy of instance is created while passing the parameter to the function. Please have a look at the following example to understand it in a better way.
static void Main(string[] args)
{
int localVar = 10;
Console.WriteLine(localVar);
MethodUsingByVal(localVar);
Console.WriteLine(localVar);
Console.Read();
}
public static void MethodUsingByVal(int intPara)
{
intPara = 20;
Console.WriteLine(intPara);
}
AS we can see from the above code example,localVar is a variable of type int which is assigned a value of 10 while initializing. At this point it creates a memory location which is assigned on local thread’s stack memory. When the value is printed it prints its value as 10.
Now the same variable is passed to the function MethodUsingByVal by value, as soon as this method is called a new memory location is called on the threads stack for the variable intPara variable. Now whatever operation we will do for the intPara, the changes are applied to the newly created memory location.
Passing Reference type by Value – Next scenario I want to discuss here is if a reference type is passed as value. In this case a copy of reference is passed to the method not the reference itself. The following example can better make you understand this concept.
static void Main(string[] args)
{
MyClass intMyClass = new MyClass();
intMyClass.LocalProperty = 10;
Console.WriteLine(intMyClass.LocalProperty);
ValForReference(intMyClass);
Console.WriteLine(intMyClass.LocalProperty);
Console.Read();
}
public static void ValForReference(MyClass myClass)
{
myClass.LocalProperty = 20;
Console.WriteLine(myClass.LocalProperty);
}
public class MyClass
{
public int LocalProperty { get; set; }
}
In the above example I have created a reference type (class) MyClass which has a property of integer type i.e. LocalProperty.
I have created an instance of the MyClass type i.e. intMyClass and assigned a value of 10 to the property. Now if I pass this variable (intMyClass) to the method ValForReference, a new variable is created on thread’s stack which will contain an already existing reference (i.e. the reference contained by intMyClass). Any changes done to this reference variables will be visible outside to the scope of this function.
But since this is just a copy of the reference, not the original reference, the changes to the reference are not visible outside the method scope as shown in the following example.
static void Main(string[] args)
{
MyClass intMyClass = new MyClass();
intMyClass.LocalProperty = 10;
Console.WriteLine(intMyClass.LocalProperty);
NullifyTheReference(intMyClass);
Console.WriteLine(intMyClass.LocalProperty);
Console.Read();
}
public static void NullifyTheReference(MyClass myClass)
{
myClass.LocalProperty = 20;
Console.WriteLine(myClass.LocalProperty);
myClass = null;
}
- Pass By Reference –
Passing value types by reference – Parameters to the methods can be passed as reference by marking the parameters with the ref or out keywords in C#. With these two keywords the reference of the variable is passed from the called function which was not the case for the parameters if they are passed by value.I will discuss about the out and ref keywords later, first let me explain about the parameter passing by reference.
static void Main(string[] args)
{
int localVar = 10;
Console.WriteLine(localVar);
MethodUsingByReference (ref localVar);
Console.WriteLine(localVar);
Console.Read();
}
public static void MethodUsingByReference(ref int intPara)
{
intPara = 20;
Console.WriteLine(intPara);
}
As we can see from the above code snippet that the value type is passed as reference which means the memory location is passed to the method, due to which we can see the changes also at the caller functions variable i.e. localVar even after when the control is returned from the called function.
Passing reference type by reference – Just like value types, reference types can also by passed by reference by using the ref keyword. It means that instead of creating a copy of the reference type, reference itself is passed to the function.
This is the main difference for reference type being passed as by val or by ref. Many people think that, it doesn’t matter for reference types by what ever way they are passed but that is not the case.
static void Main(string[] args)
{
MyClass intMyClass = new MyClass();
intMyClass.LocalProperty = 10;
Console.WriteLine(intMyClass.LocalProperty);
NullifyTheReference(ref intMyClass);
Console.WriteLine(intMyClass.LocalProperty);
}
public static void NullifyTheReference(ref MyClass myClass)
{
myClass = null;
}
As we can see from the above code example, when we are nullifying the myClass variables reference, the effect is visible in the caller functions as “Object reference not set to an instance of an object.” Exception is thrown.
Due to the same reason, we should use the ref keyword with precaution as this can lead to subtle bugs in the code, which would be difficult to point out. Please use ref keyword for reference types with caution.
Explaning out and ref keywords
As I have already discussed parameters can be passed to the function by ref by using two keywords out as well as ref. In this portion of the article I want to discuss about the main difference between these two keywords.
- The metadata emitted by the CLR for both of these keywords is same, which inturn indicates that parameter is passed by the reference no matter whichever keyword is used.
- CLR treats both of these keywords as identical which can be confirmed by my previuos point, but that is not the case with the C# compiler which treats both of these keyowrds differently.
- If the parameter is marked as out, in that case there is no need for the caller to initialize the variable. The called method is not expected to read from the paramter value without being initialized and the parameter cannot be returned without being initilized. If we are not initializing the parameter in the method, we will get the compile time error.
- If the method uses the ref keyword and is not initialized before being passed to method which expects the parameter by ref in that we will get a compile time error stating “Use of uninitialized local variable”, which we means that we need to initialize the value before using it with the ref keyword.
- It is generally preferred to use the out keyword if the varible being created is of large value type or reference type.
- We can create overloaded methods based on the ref keyword and without ref keyword as shown in the following code snippet.
public static void NullifyTheReference(ref MyClass myClass)
{
}
public static void NullifyTheReference(MyClass myClass)
{
}
- On the other hand we cannot overload the methods based on the out and ref keyword as CLR treats both of them as same. The following code snippet is totally invalid and we will get a compile time error.
public static void NullifyTheReference(ref MyClass myClass)
{
}
public static void NullifyTheReference(out MyClass myClass)
{
}
- The variables passed by reference to the methods must be of the same type as of the parameter of the method, to ensure about the type safety in .NET which I have discussed in one of my article here.
Before ending the article I would like to show the example of the out keyword
static void Main(string[] args)
{
MyClass myclassInst;
UsingTheOut(out myclassInst);
Console.WriteLine(myclassInst.LocalProperty);
Console.ReadKey();
}
public static void UsingTheOut(out MyClass myClass)
{
myClass = new MyClass();
myClass.LocalProperty = 10;
}
This was the article about the ways in which parameters can be passed to the methods in C#. Though these keywords can be easy to understand but we should use them carefully and intelligently to have some undesirable results.
The post Passing parameter by value and by reference appeared first on Dot Net For All.