Pass By Reference

You want to pass the parameter by reference to make changes. This means that the function will work with exactly the same variable as the one used in the function call, not just a variable that has the same value. Any changes made to this variable will therefore be reflected in the value of the variable used as a parameter. To do this, you simply use the ref keyword to specify the parameter:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
    class Program
        static void SumVals(ref int vals) // pass by reference
            Console.WriteLine("Before modification {0}",vals);
            vals += 10;
        static void Main(string[] args)
            int passValue = 20;
            SumVals(ref passValue); // pass by reference
            Console.WriteLine("After modification {0}",passValue);

You may also like...