2

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,730
  • 7
  • 37
  • 56
Sin
  • 1,818
  • 2
  • 16
  • 22

3 Answers3

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,100
  • 10
  • 46
  • 79
0

try this one:

 a[] dyArray = new a[]{
     new a(1),
     new a(2)
 };
VJPPaz
  • 787
  • 5
  • 19
0

How about this?

var darray = (new int[dzise]).Select(x=>new a(10)).ToArray();
Sateesh Pagolu
  • 8,769
  • 2
  • 24
  • 45