C
C#2w ago
PowerZox

Can I initialize and instance of an object in an array with its index in the array?

Below is what I want to achieve. Thanks in advance for the help. I'm a beginner so sorry if this is a very missworded question
public class MyClass
{
public MyStruct[] structArray = new MyStruct[10];
print(MyStruct[n].id);
}

public struct MyStruct
{
public int id;

public MyStruct(int i)
{
id = i; // Make `id` equal to the index of this instance in `structArray`
}
}
public class MyClass
{
public MyStruct[] structArray = new MyStruct[10];
print(MyStruct[n].id);
}

public struct MyStruct
{
public int id;

public MyStruct(int i)
{
id = i; // Make `id` equal to the index of this instance in `structArray`
}
}
And then MyStruct[n].id would equal n and it would print n.
1 Reply
Cattywampus
Cattywampus2w ago
when you 1st initialized the array, fill them up immmediately
var arr = new MyStruct[10];

for(int i = 0; i < arr.Length; i++)
{
arr[i] = new MyStruct(i);
}
var arr = new MyStruct[10];

for(int i = 0; i < arr.Length; i++)
{
arr[i] = new MyStruct(i);
}

Did you find this page helpful?