0

I'm working in Unity, and I have arrays of different types which I need to check and manipulate. After some issues with the Reference Type I found the following solution:

I have created the class "ArrayHelper" like this

public class ArrayHelper {
    public static void TrimArray<T>(ref T[] array)
    {
        T[] newArray = new T[array.Length - 1];
        for (int i = 0; i < newArray.Length; i++)
        {
            newArray[i] = array[i];
        }
        array = newArray;
    }
}

And I use this method like this:

void Start()
{
    ArrayHelper.TrimArray(ref myArray);
}

While this works, I don't think it is really elegant. I've found this thread where they show how I could do this instead:

void Start()
{
    nextPaths.Trim();
}

To do this I have changed the ArrayHelper class to this:

public static class ArrayExtensionMethods {
    public static void Trim<T>(this T[] array)
    {
        T[] newArray = new T[array.Length - 1];
        for (int i = 0; i < newArray.Length; i++)
        {
            newArray[i] = array[i];
        }
        array = newArray;
    }
}

When I call the method it doesn't change the array. I suspect this is due to references. Is there a way where I can manipulate my array like this which works properly?

Note: There are also other methods in the 'ArrayExtensionMethods' which can manipulate the array in way more complex ways. Therefore I'm looking for a general solution to my problem instead of a solution which I can only use to replace the "Trim()" method.

Animiles
  • 97
  • 7

3 Answers3

2

I can offer ref:

        public static void Trim<T>(this T[] array, ref T[] output)
        {
            T[] newArray = new T[array.Length - 1];
            for (int i = 0; i < newArray.Length; i++)
            {
                newArray[i] = array[i];
            }
            output = newArray;
        }

Use:

a.Trim(ref a);
wikiCan
  • 449
  • 3
  • 14
1

No, basically. You can't use ref on an extension method's first parameter unless it is a value-type. You'll have to return the array instead. Or... use a List<T> instead of a naked T[].

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

Ref extension methods, abysmally documented and unclear when they were introduced exactly (somewhere between C# 7.0 and 7.2), only operate on structs.

See for example C# 7.2 ref/in extension methods.

An array is not a struct, it's a reference type.

So no, you can't do this.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272