tags:

views:

94

answers:

5

I have custom object MyClass and I need to create 3 instances of it.

Instead of doing something dumb like:

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass instance3 = new MyClass();

Shouldnt I be able to do something like this:

MyClass[] instances = new MyClass();

instances[0].somemethod;

?

+7  A: 

Do it inside a loop:

MyClass[] instances=new MyClass[3];
for(int i=0;i<3;i++)
{
   instances[i]= new MyClass(); 
}

Or create the array directly:

MyClass[] instances= new MyClass[]{new MyClass(), new MyClass(), new MyClass()};
jmservera
+3  A: 
MyClass[] instances = new MyClass[3];

for (int i = 0; i < instances.Length; i++)
   instances[i] = new MyClass();
Bernard
+2  A: 

Use

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

or

MyClass[] instances = new MyClass[]{ new MyClass(), new MyClass(), new MyClass()};
codymanix
+1  A: 

Using Linq:

MyClass[] instances Enumerable.Range(0, 3).Select(_ => new MyClass()).ToArray();

The starting value 0 doesn't matter, we just want some IEnumerable with 3 elements. Alternatively Enumerable.Repeat also works, again just ignoring the first argument.

Davy8
Unnecessarily “clever” and unreadable.
Timwi
Unnecessarily clever perhaps, but hardly unreadable.
Davy8
@Timwi: errmm, what? The code is identical to the versions implementing the for loop by hand, I don't find it any more or less clever. Perhaps readability can be improved by adding line-breaks after the linq methods.
Juliet
I am not sure if its clever, but I don't think its unreadable.. however Bernard's question is what I was looking for.
smorhaim
+2  A: 

How about using LINQ?

MyClass[] instances = Enumerable.Repeat(0, 3).Select(i => new MyClass()).ToArray();

Performance considerations are left as an exercise for the reader. ;-)

Forgotten Semicolon
That's almost exactly what I had! Too late to see how many seconds apart our answers were.
Davy8
I think you actually beat me by a hair!
Forgotten Semicolon
Unnecessarily “clever” and unreadable.
Timwi
+1 concise and very readable to anyone who uses "functional .NET"
Hightechrider