Can someone help me with this Csharp Function Syntax

Trying to expand my Csharp knowledge.

How do I write this function so that I can accept any type of an array? So its not just a Transform

    public Transform[] AddToArray(Transform[] NewArray, Transform newTransform){
      
        int Length = NewArray.Length;
        Transform[] temp = new Transform[Length + 1];
        NewArray.CopyTo(temp, 0);
        NewArray = temp;
        NewArray[Length == 0 ? 0 : Length] = newTransform;
        return NewArray;
    }

Hi @Shadowing

Look into C# Generics. Would be something like this in this case:

public int[] arrInt;

void Start()
{
    arrInt = new int[] { 1, 2, 3 };

    arrInt = AddToArray(arrInt, 4);

    Debug.Log("ArrInt last element:" + arrInt[arrInt.Length - 1]);
}


public T[] AddToArray<T>(T[] arr, T newItem)
{
    int length = arr.Length;

    T[] temp = new T[length + 1];
    arr.CopyTo(temp, 0);
    arr = temp;
    arr[length == 0 ? 0 : length] = newItem;

    return arr;
}
2 Likes

What you are looking for is called a generic method (you can also have generic classes, you should be able to find some good info online about generics).
To make something generic is pretty simple, all you do is add right after the method name (or after the class name if working with classes). Then that T can be used as a Type. This is how the GetComponent method is made.

Example code: public T[] AddToArray<T> (T[] newArray, T newTransform) { ... }

A couple of things to note. It does not have to be a T, it can be anything, full normal names even. However, doing so is not considered good, or standard practice in C#.
You can also have multiple generics by simply adding a comma like you would with most things <T, K>.

Hope this was helpful, I suggest looking up more about generics, they are pretty cool. Let me know if you have any other questions! :slight_smile:

1 Like

Thanks a lot guys huge help.

thanks for the extra information @MechaWolf99
My first language is PHP so just trying get better with Csharp