How do you create a generic function for custom types that are inherited from a generic class? C#
I am looking to write a generic function to resize builtin arrays. When I use builtin arrays, they are often of a custom class, like this:
public RangedSetWeapon[] rangedSetWeapons;
And I want to create a function that works for all builtin arrays, something like this:
public static void append (Array[] originalArray, GameObject newItem) {
Array[] updatedArray = new Array[originalArray.Length] + 1;
int i = 0;
foreach (Array existingItem in originalArray) {
updatedArray[i] = existingItem;
i += 1;
}
updatedArray[i] = newItem;
return updatedArray;
}
But this obviously wont work because the originalArray type is unknown, as is the type of the newItem object.
Is there a way to generisize this code so it would work for ANY builtin array using ANY object type (as long as it matches the originalArray type)?
Any thoughts would be appreciated
Thanks to @FortisVenaliter - this function works perfectly:
public static T[] append <T> (T[] originalArray, T newItem) {
T[] updatedArray = new T[originalArray.Length + 1];
for (int i = 0; i < updatedArray.Length-1; i++) {
updatedArray[i] = originalArray[i];
}
updatedArray[updatedArray.Length-1] = newItem;
return updatedArray;
}
Answer by FortisVenaliter · May 06, 2016 at 05:40 PM
Yep, and it's called (drum roll please) C# Generics. Basically, you can include one or more type parameters in your function calls that will allow you to determine the type at runtime and execute. Of course, not knowing the type ahead of time limits your functionality. There are a bunch of resources online if you search, but the basic function header would look something like this:
public static void append<T>(T[] originalArray, T newItem) {...
In this case, the function is using the stand-in type variable 'T' to represent they type.
On a separate note though, if you are looping with an index, you should really use the old-school 'for' instead of the memory hog 'foreach'.
Epic! Thanks so much for the clear response. Works perfectly.
Thank you also for the memory tip!