Search code examples
c#delegatesref

why delegate work as ref?


I have program

    public delegate T Transformer<T>(T arg);
    public class Util
    {
        public static void Transform<T>(T[] values, Transformer<T> t)
        {
            for (int i = 0; i < values.Length; i++)
                values[i] = t(values[i]);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = { 1, 2, 3 };
            Util.Transform(values, Square); // Hook in Square
            foreach (int i in values)
            Console.Write(i + " "); // 1 4 9
            Console.ReadLine();
        }
        static int Square(int x) => x * x;
    }

Why Util.Transform(values, Square) changes values[] array? It is already works like reference variable. I just wanna yo see output result not changing the source array named "values[]".


Solution

  • You can change the method like that:

    public class Util
    {
        public static T[] Transform<T>(T[] values, Transformer<T> t)
        {
            return values.Select(x => t(x)).ToArray();
        }
    }
    

    Then you can call it like

    var result = Utils.Transform(values, Square);
    

    If you can't change that method, then you need to copy the array before calling:

    var result = values.ToArray();
    Utils.Transform(result, Square);