1

This is my question: Let's say I have a class with such a constructor:

Class A {
   private int i;
   public A(int new_i) {
      i = new_i;
   }
}

Can I initialize an array of A with an array of int? If so, how can I do it? I was thinking something like:

int[] b = new int[5] { 0,1,2,3,4}; 
A[] a; 
a = new A[](b);

Thanks!

2 Answers 2

6
var a = Array.ConvertAll(b, item => new A(item));

The advantage here is that it will be created with the right size, without any intermediate steps - plus it works without LINQ.

In C# 2.0 it is a bit uglier - the following is identical:

A[] a = Array.ConvertAll<int,A>(b,
    delegate(int item) { return new A(item); });

The combination of var, lambdas, and improved generic type inference really shine for C# 3.0 here.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for ConvertAll. BTW, the complexity of the 2nd version IMHO suggest to use an old-good for loop in C# 2.0 (it's just a couple of lines of code...)
3

You could use LINQ:

int[] b = new int[5] { 0, 1, 2, 3, 4 }; 
A[] a = b.Select(x => new A(x)).ToArray(); 

Comments

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.