is it possible to create a generic ReDim function in C# that will take in any data type? creating a ReDim function for a single data type is easy, but handling any data type seems to be confusing.
Printable View
is it possible to create a generic ReDim function in C# that will take in any data type? creating a ReDim function for a single data type is easy, but handling any data type seems to be confusing.
I assume you are concerned about the "Preserve" keyword, because you don't need a ReDim function if you don't want to preserve. Just assign a new Array object to your variable:Also, the Array.Copy method can achive what ReDim Preserve does in just a few lines anyway:Code:int[] myArray = new int[10];
myArray = new int[20];
I'm not sure you can do it any other way, because you cannot convert back and forth between an Array object and an array of a particular type of objects.Code:int[] myArray = new int[5];
int[] tempArray = new int[10];
Array.Copy(myArray, 0, tempArray, 0, Math.Min(myArray.Length, tempArray.Length));
myArray = tempArray;
i guess it would have to be a separate function for each type of array.
It sounds like you want templates. Something I don't think C# has. But you might be able to pull it off using Interface, but it depends on what you want to do. But templates would be the best.
- ØØ -
Or you also might be able to do it with the Object class, since after all, in C# EVERY object is derived somehow from Object.
Code:using System;
class MainClass{
public static void Main(string[] args){
Object[] array = new Object[5];
for (int i = 0; i < 5; i++){
array[i] = i;
}
Object[] tempArray = new Object[10];
Array.Copy(array, 0, tempArray, 0, Math.Min(array.Length, tempArray.Length));
array = tempArray;
for (int i = 0; i < 10; i++){
Console.WriteLine("Array[i]: " + array[i]);
}
}
}
Visual Studio 2005 Has the Generic namespace wthich is pretty much exactly like C++ template. So you'll be able to have a single Redim function in C# that can handle any array type.
2005 rules.
Yeah, make him wait untill C# 2.0 is out..:D
- ØØ -
I'm sure it's not as efficient as a standard Array but how about using an ArrayList that automatically resizes as needed?
DJ
an arraylist sounds like the way to go.
thanks.