C# Pass By Value with Examples

  Total Views : 90
  Comments : 0
  Keywords : C# parameters passing by value method with examples, C# call by value to pass a copy of the variable to the method with examples

HTML Source EditorWord Wrap

Here we will learn passing parameters by value or call by value in c# with examples and how to use c# pass by value or call by value to pass a value type parameters by value with examples.

C# Passing Parameters By Value

In c#, Passing a Value-Type parameter to a method by value means passing a copy of the variable to the method. So the changes made to the parameter inside of called method will not have an effect on the original data stored in the argument variable.

 

As discussed earlier, Value-Type variables will contain the value directly on it memory and Reference-Type variables will contain a reference of its data.

C# Passing Parameters By Value Example

Following is the example of passing a value type parameter to a method by value in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            int x = 10;

            Console.WriteLine("Variable Value Before Calling the Method: {0}", x);

            Multiplication(x);

            Console.WriteLine("Variable Value After Calling the Method: {0}", x);

            Console.WriteLine("Press Any Key to Exit..");

            Console.ReadLine();

        }

        public static void Multiplication(int a)

        {

            a *= a;

            Console.WriteLine("Variable Value Inside the Method: {0}", a);

        }

    }

}

If you observe above example, the variable x is a value type and it passed to the Multiplication method. The content of variable x, copied to the parameter a and made required modifications in Multiplication method but the changes that made inside of the method have no effect on the original value of the variable.

Output of C# Passing Parameters By Value Example

When we execute above c# program, we will get the result like as shown below.

 

C# Pass By Value Example Result

 

If you observe above result, the variable value not changed even after we made the modifications in our method.

 

This is how we can pass parameters to the method by value in c# programming language based on our requirements.

 Comments (0)

Be the first to give your valuable feedback

  • Default Tutlane User