2

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;

?

5 Answers 5

7

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()};
Sign up to request clarification or add additional context in comments.

Comments

3
MyClass[] instances = new MyClass[3];

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

Comments

2

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()};

Comments

2

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. ;-)

3 Comments

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

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.

2 Comments

@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.
I am not sure if its clever, but I don't think its unreadable.. however Bernard's question is what I was looking for.

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.