Reputation: 987
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!
Upvotes: 1
Views: 252
Reputation: 1064064
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.
Upvotes: 6
Reputation: 1039428
You could use LINQ:
int[] b = new int[5] { 0, 1, 2, 3, 4 };
A[] a = b.Select(x => new A(x)).ToArray();
Upvotes: 3