This is a premium alert message you can set from Layout! Get Now!

Pass by Value & Pass by Reference

0

C# Pass by Value & Pass by Reference


C#: Pass by Value & Pass by Reference

In C#, there are two ways to pass parameters to a method - by value and by reference. Understanding the difference between these two methods is crucial for writing efficient and effective C# code.

Pass by Value

Passing by value is the default method in C#. When a method is called with a parameter passed by value, a copy of the value is made and stored in a new memory location. Any changes made to the parameter within the method do not affect the original value outside the method.

Example:
int num = 5;
        Console.WriteLine("Before calling the method: " + num);
        UpdateValue(num);
        Console.WriteLine("After calling the method: " + num);
        
        static void UpdateValue(int val)
        {
          val = val + 10;
        }

Output:
Before calling the method: 5
After calling the method: 5

Pass by Reference

Passing by reference is a method in which the reference to the original value, rather than a copy of the value, is passed to the method. Any changes made to the parameter within the method affect the original value outside the method.

In C#, the "ref" and "out" keywords are used to pass parameters by reference. The "ref" keyword is used when the method requires that the parameter passed be initialized before the method call. The "out" keyword, on the other hand, is used when the method is expected to initialize the parameter within the method.

Example using the "ref" keyword:
int num = 5;
        Console.WriteLine("Before calling the method: " + num);
        UpdateValueRef(ref num);
        Console.WriteLine("After calling the method: " + num);
        
        static void UpdateValueRef(ref int val)
    	{
        	val = val + 10;
    	}

Output:
Before calling the method: 5
After calling the method: 15


Example using the "out" keyword:
int num;
        Console.WriteLine("Before calling the method: " + num);
        UpdateValueOut(out num);
        Console.WriteLine("After calling the method: " + num);
        
        static void UpdateValueOut(out int val)
    	{
        	val = 15;
    	}

Output:
Before calling the method: 
After calling the method: 15

In conclusion, understanding the difference between passing by value and by reference, as well as the use of the "ref" and "out" keywords in C#, is essential for writing efficient and effective code. It is important to choose the correct method for passing parameters based on the specific requirements of the method and the desired behavior of the program.
Tags

Post a Comment

0 Comments
Post a Comment

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!
To Top