Click here to Skip to main content
15,867,453 members
Articles / All Topics
Technical Blog

Passing parameter by value and by reference

Rate me:
Please Sign up or sign in to vote.
4.85/5 (4 votes)
31 Aug 2015CPOL6 min read 6.4K   1
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.

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#.


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#.

  1. Pass by Value
  2. Pass by reference.

I want to discuss both of these ways here one by one

  1. 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);//print 10
                MethodUsingByVal(localVar);//prints 20
                Console.WriteLine(localVar);//prints 10
                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); //prints 10
                ValForReference(intMyClass); //prints 20
                Console.WriteLine(intMyClass.LocalProperty); //prints 20
                Console.Read();
            }   
             /// <summary>
             /// The method accepts the instance of MyClass type which is passed by value.
             /// </summary>
           	 /// <param name="myClass"></param>
            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); //prints 10
               NullifyTheReference(intMyClass); 
               Console.WriteLine(intMyClass.LocalProperty); //The reference is not null and still prints 20
               Console.Read();
            }
    
            public static void NullifyTheReference(MyClass myClass)
            {
               myClass.LocalProperty = 20;
           	   Console.WriteLine(myClass.LocalProperty);
               myClass = null; // we are setting the myClass variable as null
            }

  2. 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);//prints 10
                    MethodUsingByReference (ref localVar);//prints 20
                    Console.WriteLine(localVar);//prints 20
                    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); //prints 10
             NullifyTheReference(ref intMyClass);
             Console.WriteLine(intMyClass.LocalProperty); //Exception "Object reference not set to an instance of an object."        Console.Read();
          }
          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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. It is generally preferred to use the out keyword if the varible being created is of large value type or reference type.
  6. 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)
            {
                
            }
  7. 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)
            {
                
            }
  8. 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);//using the uninitialized variable myclassInst
                Console.WriteLine(myclassInst.LocalProperty);//prints 10
                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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I have 8 years of experience of mostly developing the .NET windows as well as web applications. Passionate about learning and sharing.

Visit my personal blog to know more about the .NET technology and increase your knowledge about C# and .NET. You can always follow me on twitter @dotnetforall.

Comments and Discussions

 
-- No messages could be retrieved (timeout) --