© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•13mo ago•
1 reply
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
MyStruct[n].id
would equal
n
n
and it would print
n
n
.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Object reference set to an instance of an object.
C#CC# / help
3y ago
✅ Object reference not set to an instance of an object.
C#CC# / help
10mo ago
"Object reference not set to an instance of an object"
C#CC# / help
17mo ago
Object reference not set to an instance of an object.
C#CC# / help
2y ago