1

How to initialize an array of objects by calling the parameterized constructor of the class

Example:

class a
{
    int val;

    //def
    public a()
    {
    }

    //with param
    public a(int value)
    {
        val = value;
    }
}

How to initialize a dynamic array of the above class by using its constructor

eg:

a[] dyArray = new a[size];  // how to call constructor to initialize a value 
                            // other than looping each element and initialize 
                            // it? say, with value 10;

Is there any other standard way to do this?

NASSER
  • 5,900
  • 7
  • 38
  • 57
Sin
  • 1,836
  • 2
  • 17
  • 24

4 Answers4

1

If you can use a generic list instead you can create the collection and initialise a value:

List<a> aList = new List<a>
{
    new a(10)
};

https://msdn.microsoft.com/en-us/library/bb384062.aspx

Steve
  • 9,335
  • 10
  • 49
  • 81
0

try this one:

 a[] dyArray = new a[]{
     new a(1),
     new a(2)
 };
VJPPaz
  • 917
  • 7
  • 21
0

The good old way is like this:

a** dyn_arr_ptr = new a*[size];
for (i = 0; i < size; ++i) {
  dyn_arr_ptr[i] = new a(10); // or it could "new a(i)" more flexibility here in parameter value per instance
}
Pradeep Kumar
  • 1,193
  • 1
  • 9
  • 21
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '22 at 17:14
-1

How about this?

var darray = (new int[dzise]).Select(x=>new a(10)).ToArray();
Sateesh Pagolu
  • 9,282
  • 2
  • 30
  • 48