hoo_man
hoo_man

Reputation: 11

How to initialize an array of custom type?

How can I make an array with 400 elements of type myClass and pass different args to each of them?

I have two classes: mainClass and myClass. I want to create the array in mainClass. as you can see myClass needs 3 args.

myClass:

namespace prj1
{
    class myClass
    {
        public myClass(int A, int B int C)
        {
            ...
            ...
            ...
        }
    }
}

mainClass:

namespace prj1
{
    class mainClass
    {
        public myClass[] myVar = new myClass[400];

        public mainClass(int y, int m, int d)
        {
            ...
            ...
            ...
        }
    }
}

If I have to use setValue to initialize them how can I do this? How should I pass 3 args?

for (int i = 0; i < 400; i++)
            {
                myVar.SetValue(object Value, i);
            }

Upvotes: 0

Views: 3036

Answers (3)

Habib
Habib

Reputation: 223207

for (int i = 0; i < 400; i++)
{
    myClass tempObject = new myClass(y,m,d);
    myVar.SetValue(tempObject,i)
}

Upvotes: 1

Jason Larke
Jason Larke

Reputation: 5599

Why don't you just construct each instance within the loop you already have?

for(int i = 0; i < myVar.Length; i++)
{
    myVar[i] = new myClass(arg1, arg2, arg3);
}

You have an appropriate constructor already, and you're initializing within a loop... 1 + 1 == 2, let's not try and reinvent the wheel shall we?

Upvotes: 5

KV Prajapati
KV Prajapati

Reputation: 94635

Try this,

for (int i = 0; i < 400; i++)
 {
   myVar[i]=new MyClass(y,m,d);
 }

//or

for (int i = 0; i < 400; i++)
 {
   myVar.SetValue(new MyClass(y,m,d),i);
 }

Upvotes: 1

Related Questions