Thorin Oakenshield
Thorin Oakenshield

Reputation: 14682

Dynamic Initialize in c#

I've a class

class sampleClass
{
    ...........
    ...........
    public sampleClass()
    {.........}
}

and in another class i created an array like

sampleClass[] X=new sampleClass[]{new sampleClass(),new sampleClass()}

here i gave 2 instance of the constructor. i need this dynamically..

that is the size of the array should be dynamically changed

Upvotes: 0

Views: 277

Answers (3)

Martin Liversage
Martin Liversage

Reputation: 106906

You can initialize the array using a loop:

sampleClass[] X = new sampleClass[123];
for (int i = 0; i < X.Length; ++i)
  X[i] = new sampleClass();

If your class was a value type the array is initialized when it is allocated:

struct sampleStruct { ... }

sampleStruct[] X = new sampleStruct[123];
// No need to initialize every array cell.

However, using a struct instead of a class is not something you should do simply to avoid a loop. You can read more about value types on MSDN.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502406

It sounds like you want something like:

int size = // whatever

SampleClass[] array = new SampleClass[size];
for (int i = 0; i < size; i++)
{
    array[i] = new SampleClass();
}

EDIT: If you really want to avoid a for loop, you could do something like:

SampleClass[] array = Enumerable.Range(0, size) 
                                .Select(x => new SampleClass())
                                .ToArray();

... but I don't think that's actually better than using a loop.

Upvotes: 1

Elisha
Elisha

Reputation: 23780

This is just a syntactic sugar, you can gain the same using your own code:

sampleClass[] X = new sampleClass[num];
for(int i = 0; i < num; i++)
{
   X[i] = new sampleClass();
}

Upvotes: 0

Related Questions