0

I got a class which holds an array and another object:

public class MyClass
{
    public double[] myArray;
    public int otherObject;
};

Now I want to create different array instances of that class:

static void Main(string[] args)
{
    MyClass[] classArray1 = new MyClass[classArraySize1]
    MyClass[] classArray2 = new MyClass[classArraySize2]
};

But how do I size myArray for every classArray individually?

They should be assigned values like this later:

classArray1[i].myArray[j] = 1.0;
classArray2[n].myArray[k] = 2.0;
1
  • What is the question? Btw you've not even initialized your array with instances of MyClass. Commented Jan 25, 2016 at 17:44

4 Answers 4

1

You can add a constructor to your class that you can use to initialize the array to a given size:

public class MyClass
{
    public double[] myArray;
    public int otherObject;

    public MyClass(int size)
    {
        myArray = new double[size];
    }
}

You can then set the size of myArray for an array of MyClass with something like:

int numMyClasses = 123;
int sizeMyArray = 456;

// Manually
MyClass[] classArray1 = new MyClass[numMyClasses];
for (int i = 0; i < numMyClasses; i++)
    classArray1[i] = new MyClass(sizeMyArray);

// LINQ
MyClass[] classArray2 = new MyClass[numMyClasses]
    .Select(x => new MyClass(sizeMyArray)).ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Lol. You arnt reinventing the wheel... you are building a time machine :D.
0

You can set them on the fly like this

static void Main(string[] args)
{
    MyClass[] classArray1 = new MyClass[classArraySize1]
    MyClass[] classArray2 = new MyClass[classArraySize2]

    classArray1[i].myArray = new double[whatever_size_you_want];
    classArray2[i].myArray = new double[whatever_size_you_want];
};

Comments

0

You can use this:

MyClass[] classArray1 =
{
    new MyClass { myArray = new double[classArraySize1] },
    new MyClass { myArray = new double[classArraySize1] }
};

MyClass[] classArray2 =
{
    new MyClass { myArray = new double[classArraySize2] },
    new MyClass { myArray = new double[classArraySize2] }
};

Comments

0

A constructor is (in my opinion) the best way to go.

public class MyClass
{
    public double[] myArray;
    public int otherObject;

    public MyClass(int ArraySize)
    {
        myArray = new double[ArraySize];
    }
}

static void Main(string[] args)
{
    MyClass custom1 = new MyClass(10); // <-- new instance of your class
    custom1.myArray // <-- holds your array
    custom1.otherObject // <-- holds your object
}

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.