0

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);
            }
3
  • I dont see a public method SetValue defined in your myClass class? Commented Jun 25, 2012 at 6:48
  • 1
    @JohnGathogo: SetValue is a method of array class... Commented Jun 25, 2012 at 7:01
  • It sounds to me like you need to rethink the way you're doing things. If you need to fill an array with different objects, you're probably keeping track of them in an array or an ArrayList or something like that. If not, I've found your problem. Commented Jun 25, 2012 at 13:55

3 Answers 3

5

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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);
 }

1 Comment

tnx. In setValue method I missed the "new" keyword. tnx a lot.
1
for (int i = 0; i < 400; i++)
{
    myClass tempObject = new myClass(y,m,d);
    myVar.SetValue(tempObject,i)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.