CSharp - Passing Value Type by Value


A value type variable directly contains its data, and a reference type variable contains a reference to its data.

Passing a value type variable to a method by value means that we are actually passing a copy to the method.

If the method makes any change on that copied parameter, it has no effect on the original data.

If you wish that the change made by the caller method reflects back to original data, you need to pass it by reference with either a ref keyword or an out keyword.


using System;
class Program//ww  w.  j ava 2  s  .  c  om

    static void Change(int x)
        x = x * 2;
        Console.WriteLine("Inside Change(), myVariable is {0}", x);//50
    static void Main(string[] args)
        int myVariable = 25;
        Console.WriteLine("Inside Main(), myVariable={0}", myVariable);//25



We made a change inside the Change() method.

But this changed value is not reflected outside the Change() method.

This is because actually the change made was on the copy of myVariable and the effect of changing was only on the local variable x.

Related Topic