I am trying to initialize a newly created empty array by using a method. Example below. This is the structure of the code that I want to create.
var v = exClass[5,5];
v.ExtensionMethodThatWillInitilize();
What I want ExtensionMethodThatWIllInitilize to do is following:
for(int y = 0 ; y < exClass.getLength(0); y++ ) {
for(int x = 0 ; x < exClass.getLength(1); x++ ) {
v[y,x] = new instanceObject();
}}
So I came up with below code...
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var oldEx = new ExClass[10, 10];
var newEx = oldEx.init();
}
}
public class ExClass
{
public string exString
public ExClass() {
exString = " I AM NEW! YES! ";
}
}
public static class tools
{
static public ExClass[,] init(this ExClass[,] start)
{
var newArray = new ExClass[start.GetLength(0), start.GetLength(1)];
for (int y = 0; y < start.GetLength(0); y++)
{
for (int x = 0; x < start.GetLength(1); x++)
{
newArray[y, x] = new ExClass();
}
}
return newArray;
}
}
Yet the problem is that I do not know how to modify my init method so that it can take any type of array and return corresponding array that had been initialize. I tried to use generic type T but my lack of experience seems to fail.
Summery:
1) how do you come up with a method that will initialize an empty array in a single step.
2) how do you make sure that the method can initialize any type of array(assuming that the element in the array has a constructor that does not take any argument)