472,986 Members | 2,687 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,986 software developers and data experts.

Initializing object arrays.

Is there any way to initialize an array of objects without looping
through each elements?

Class A
{
private int PrivateValue;
public A(int a)
{
PrivateValue=a;
}
}

void Main()
{
A[] arrayA=new A[100];
//At this point, A[0]~A[99] are all nulls
foreach(A a in arrayA) {a=new A(0); }
}

I've been using that kind of code. Is there any precise code? Long
time ago, I hoped
A[] arrayA=new A[100](0);
would work, but it didn't.
Aug 25 '08 #1
8 5226
On Sun, 24 Aug 2008 17:55:46 -0700, Sin Jeong-hun <ty*******@gmail.com>
wrote:
Is there any way to initialize an array of objects without looping
through each elements?
That depends. What version of .NET are you using? If you have .NET 3.5,
you can use LINQ:

A[] arrayA = Enumerable.Repeat(new A(0), 100).ToArray();

Probably less efficient performance-wise than doing it yourself, but it
does read better.

It might be considered a little awkward, but you can use the
Array.ConvertAll() method for similar purpose:

A[] arrayA = Array.ConvertAll(new A[100], delegate { return new A(0);
});

That's available in .NET 2.0, and maybe almost as efficient as an explicit
loop (there's an extra throw-away array allocated, but otherwise should be
about the same). Not quite as expressive as the LINQ version though.
[...]
void Main()
{
A[] arrayA=new A[100];
//At this point, A[0]~A[99] are all nulls
foreach(A a in arrayA) {a=new A(0); }
}

I've been using that kind of code.
I hope not. :) In that code, "a" is read-only and even if you could
assign to it, it wouldn't change the value in the array, just the variable
"a".

You probably meant:

for (int i = 0; i < arrayA.Length; i++)
{
arrayA[i] = new A(0);
}

Hopefully the LINQ version should work for you. Even if it doesn't, if
the explicit pattern bothers you, it would be relatively easy for you to
write a generic method to do the array initialization for you.

Pete
Aug 25 '08 #2
Oh yeah, I forgot that I cannot modify the collection inside the
foreach statement. Thank you for all the explations. I'll start
learning LINQ.

But still, I think
A[] arrayA=new A[100](0);
is more intuitive.

On Aug 25, 10:22*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Sun, 24 Aug 2008 17:55:46 -0700, Sin Jeong-hun <typing...@gmail.com*
wrote:
Is there any way to initialize an array of objects without looping
through each elements?

That depends. *What version of .NET are you using? *If you have .NET 3.5, *
you can use LINQ:

* * *A[] arrayA = Enumerable.Repeat(new A(0), 100).ToArray();

Probably less efficient performance-wise than doing it yourself, but it *
does read better.

It might be considered a little awkward, but you can use the *
Array.ConvertAll() method for similar purpose:

* * *A[] arrayA = Array.ConvertAll(new A[100], delegate { return new A(0); *

});

That's available in .NET 2.0, and maybe almost as efficient as an explicit *
loop (there's an extra throw-away array allocated, but otherwise should be *
about the same). *Not quite as expressive as the LINQ version though.
[...]
void Main()
{
* A[] arrayA=new A[100];
* //At this point, A[0]~A[99] are all nulls
* foreach(A a in arrayA) {a=new A(0); }
}
I've been using that kind of code.

I hope not. *:) *In that code, "a" is read-only and even if you could*
assign to it, it wouldn't change the value in the array, just the variable *
"a".

You probably meant:

* * *for (int i = 0; i < arrayA.Length; i++)
* * *{
* * * * *arrayA[i] = new A(0);
* * *}

Hopefully the LINQ version should work for you. *Even if it doesn't, if*
the explicit pattern bothers you, it would be relatively easy for you to *
write a generic method to do the array initialization for you.

Pete
Aug 25 '08 #3
Peter Duniho wrote:
>Is there any way to initialize an array of objects without looping
through each elements?

That depends. What version of .NET are you using? If you have .NET
3.5, you can use LINQ:

A[] arrayA = Enumerable.Repeat(new A(0), 100).ToArray();
That will create an array with 100 references to the same object, won't it?

--
Göran Andersson
_____
http://www.guffa.com
Aug 25 '08 #4
Sin Jeong-hun wrote:
But still, I think
A[] arrayA=new A[100](0);
is more intuitive.
One major reason that there is no such shortcut is probably that it's
usage is very limited. The only thing that you can use it for is to
create an array containing identical objects, which isn't really
something that you do very often.

--
Göran Andersson
_____
http://www.guffa.com
Aug 25 '08 #5
On Sun, 24 Aug 2008 23:50:24 -0700, Göran Andersson <gu***@guffa.com>
wrote:
Peter Duniho wrote:
>>Is there any way to initialize an array of objects without looping
through each elements?
That depends. What version of .NET are you using? If you have .NET
3.5, you can use LINQ:
A[] arrayA = Enumerable.Repeat(new A(0), 100).ToArray();

That will create an array with 100 references to the same object, won't
it?
Um. Yes. I guess that's probably not what the OP wanted, is it? At
least that's not what his code showed.

Sorry...I must've still been a little sleepy when I wrote that. :) The
Array.ConvertAll() solution should work fine though. And maybe there's a
LINQ approach I'm not thinking of yet. It's a shame that the Repeat()
method takes just a single object, and that there's not an overload you
can pass a delegate to.

Maybe something like:

A[] arrayA = new A[100].Select(x =new A(0)).ToArray();

That's starting to get a little awkward itself though, and not much
different from the ConvertAll() version.

Oh well...rambling now...

Pete
Aug 25 '08 #6
On Aug 25, 11:28*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
Sorry...I must've still been a little sleepy when I wrote that. *:) *The *
Array.ConvertAll() solution should work fine though. *And maybe there'sa *
LINQ approach I'm not thinking of yet. *It's a shame that the Repeat() *
method takes just a single object, and that there's not an overload you *
can pass a delegate to.

Maybe something like:

* * *A[] arrayA = new A[100].Select(x =new A(0)).ToArray();
Enumerable.Range(0, 100).Select(x =new A(0)).ToArray();
Aug 26 '08 #7
On Tue, 26 Aug 2008 07:51:14 -0700, Pavel Minaev <in****@gmail.comwrote:
[...]
>Maybe something like:

Â* Â* Â*A[] arrayA = new A[100].Select(x =new A(0)).ToArray();

Enumerable.Range(0, 100).Select(x =new A(0)).ToArray();
Ah, I was so close. But I prefer:

Enumerable.Repeat(0, 100).Select(x =new A(0)).ToArray();

Or even:

Enumerable.Repeat(0, 100).Select(x =new A(x)).ToArray();

Why make LINQ do any math when it's not necessary? :)

Pete
Aug 26 '08 #8
On Aug 26, 8:00*pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Tue, 26 Aug 2008 07:51:14 -0700, Pavel Minaev <int...@gmail.comwrote:
[...]
Maybe something like:
* * *A[] arrayA = new A[100].Select(x =new A(0)).ToArray();
Enumerable.Range(0, 100).Select(x =new A(0)).ToArray();

Ah, I was so close. *But I prefer:

* * *Enumerable.Repeat(0, 100).Select(x =new A(0)).ToArray();

Or even:

* * *Enumerable.Repeat(0, 100).Select(x =new A(x)).ToArray();

Why make LINQ do any math when it's not necessary? *:)
Still too verbose for my liking, so I've opened a VS Connect ticket
for Enumerable.Generate:

https://connect.microsoft.com/Visual...dbackID=363960

Come by and vote! :)
Aug 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: pmatos | last post by:
Hi all, I have a vector of vector of ints, I could use C approach by using int but I think C++ vector<vector<int> > would be easier to manage. So I have a function which creates and initializes...
4
by: Mantorok Redgormor | last post by:
Is this legal? int foo = { 0 }; gcc gives: foo.c: In function `main': foo.c:5: warning: missing braces around initializer foo.c:5: warning: (near initialization for `foo') foo.c:5:...
10
by: Steve | last post by:
this code: private Array m_arrays = new Array; results in an array of 3 null Array objects. What am I missing?
12
by: jimmij | last post by:
Hi, Please look at the code bellow /*******************/ class ctab { private: static const unsigned n=48;
11
by: sg71.cherub | last post by:
Hi All, I have encapsulate CvMat of OpenCV into my own matrix class as the following: class CVMatrix { //== Fields private: unsigned m_Width;
13
by: John | last post by:
Is this a valid C++ program that will not crash on any machine? #include <iostream> using namespace std; int main( void ) { int i; cin >i; double X; X = 1123;
12
by: Mik0b0 | last post by:
Hallo. Let's say, there is a structure struct struct10{ int a1; int a2; int a3; int a4; }count={ {10,20,30,40}, {50,60,70,80}
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
4
by: Peskov Dmitry | last post by:
class simple_class { int data; public: simple_class() {data=10;}; simple_class(int val) : data(val){} }; int main() {
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.