Search code examples
c#visual-studioreferenceref

Get value from table as a reference


In c++ it`s possible to do it by reference (&) or pointer (*). In C# there is "ref". How to get value from table and change it by reference to it?

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] t=new int[3]{1,2,3};
            int a=t[0]; //ref int a=t[0];
            a+=10;
            System.Console.WriteLine("a={0}", a);   //11
            System.Console.WriteLine("t[0]={0}", t[0]); //1
        }
    }
}

E.g. in c++

int &a=tab[0];

Solution

  • This has only become feasible in C# 7, using ref locals:

    public class Program
    {
        public static void Main(string[] args)
        {
            int[] t = {1, 2, 3};
            ref int a = ref t[0];
            a += 10;
            System.Console.WriteLine($"a={a}");       // 11
            System.Console.WriteLine($"t[0]={t[0]}"); // 11
        }
    }
    

    This is the important line:

    ref int a = ref t[0];
    

    C# 7 also supports ref returns. I would advise using both features sparingly - while they can certainly be useful, they will be unfamiliar to many C# developers, and I can see them causing significant confusion.