472,779 Members | 1,812 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,779 software developers and data experts.

(Re): Which constructor is used when instantiating an array of objs ?

Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway,
although Ollie's answer makes perfectly sense when dealing with
classes, it doesn't seem to me to apply as well if you have to
instantiate an array of structures; consider the following useless
code :
using System;

struct MyPointS
{
internal int x;
internal int y;
internal static int a=-1;

static MyPointS()
{ Console.WriteLine("static constr."); }

public MyPointS(int t)
{ Console.WriteLine("1 args constr."); x=y=t; }
}

public class David
{
public static void Main()
{
int ss=MyPointS.a;
// causes static constructor to run

MyPointS s1=new MyPointS();
// causes implicit default 0 args constructor to run

MyPointS s2=new MyPointS(11);
// causes 1 args constructor to run

MyPointS[] vs=new MyPointS[5];
// no explicit constructor seems to run.
// With structures (as opposed to classes) instances
// in the array DO_GET_ALLOCATED
// (on the stack, as opposed to heap),
// so that you can do the following :

vs[3].x=vs[3].y=123;
// if MyPointS weren't a structure, but a class,
// this line would cause an exception to be raised
}
}

So the basic question is the same :

"How can I instantiate an array of objects (out of a struct),
specifying - as I do when creating single objects - which constructor
should be run, to let, for instance, the array elements (or anythinhg
else) being initialized the way I want ?"

Ollie's previous answer for classes, adapted to structures

MyPointS[] vs=new MyPointS[5];
vs[3]=new MyPointS(11);

seems to suggest that, to achieve that, you happen to instantiate
twice a given object :
When you declare the array object

MyPointS[] vs=new MyPointS[5];
// five structure objs get "physically" allocated on the stack
And when you explicitely call a costructor for a given array element

vs[3]=new MyPointS(11);
// a new vs[3] obj overwrites the one previously
// created when the array was first allocated
So, it seems "anti-economical" to me having to re-create the same
object (out of a structure definition), if you just want to have it
properly initialized.

Sorry to return again on such a basic trivial topic, but I'd like to
understand if that's a (minor) flaw of the language, or, more likely,
something basic I still can't catch.
Thanks, David

"Ollie" <ol**********@hotmail.com> wrote in message

MyPointC[] vc=new MyPointC[5];

does not allocate any instances in the array, it only cretaes the
System.Array object so therefore none of the MyPointC constructors are
called.

you would have to do:

MyPointC[] vc=new MyPointC[5];
vc[0] = new MyPointC();
vc[1] = new MyPointC(11);
vc[1] = new MyPointC(22222);

HTH

Ollie Riches

"david" <fa*********************@yahoo.it> wrote in message
news:23**************************@posting.google.c om...
I have a question (not sure if just a newbie one, or a stupid one)
whose answer I couldn't find on the C# books and tutorials I could put
my hands on.

Consider the following useless class (could be a struct as well, if
you just comment out the non static parameterless constructor) and the
Main() routine :

using System;

class MyPointC
{
int x;
int y;
internal static int a=-1;

static MyPointC()
{ Console.WriteLine("static constr."); }

public MyPointC()
{ Console.WriteLine("0 args constr."); x=1; y=2;}

public MyPointC(int t)
{ Console.WriteLine("1 args constr."); x=y=t; }
}

public class David
{

public static void Main()
{
int cc=MyPointC.a;
// causes static constructor to run

MyPointC c1=new MyPointC();
// causes 0 args constructor to run

MyPointC c2=new MyPointC(11);
// causes 1 args constructor to run

MyPointC[] vc=new MyPointC[5];
// no explicit constructor seems to run
}
}

The question is :
"How can I instantiate an array of objects (both from a class or a
struct), specifying - as I do when creating single objects - which
constructor should be run, to let, for instance, the array elements
(or anythinhg else) being initialized the way I want ?"
MyPointC[] vc=new MyPointC()[5];
or
MyPointC[] vc=new MyPointC[5]();

are both invalid syntax, rejected by the compiler.
Am I missing a basic thing or two ?!?
Thanks, David

Nov 16 '05 #1
2 2127
Arrays are reference types and are allocated on the managed heap, not on the
stack. It does not matter what the element type is: reference type or value
type - the array is still on the heap.

An array of a struct type (i.e. a value type) will have each element
initialized to the default value for that type. The language spec defines it
this way:

"the default value of a struct is the value produced by setting all value
type fields to their default value and all reference type fields to null."
(Section 11.3.4 even shows an example of an array.)

You can think of it as if the "default constructor" is run for each element
of the array. Remember though, for a struct, you cannot write the default
constructor, the compiler always writes it for you so you will not be able to
put a print statement inside to see it called.
Nov 16 '05 #2
When you allocate an array the runtime zeros the memory - fullstop.

So for reference types you get an array of null references and for value types (structs) you get an array of zeroed value types. This is the reason behind why you cannot declare a custom *default* constructor on a value type - if you did the runtime would have to execute it as many times as there are members of the array - which could be a significant hidden overhead in array allocation.

Also, when you write the code

MyStruct[] s = new MyStruct[100];
s[23] = new MyStruct(40, 2);

the second line is not creating anything, its simply re-initializing an already allocated block of memory. So while, in theory, running the contructor as part of array allocation using the (made up) syntax

MyStruct[] s = new MyStruct[100](40, 2); // REPEAT: I HAVE JUST INVENTED THIS SYNTAX

causes the constructor to run 100 times - so does the following.

MyStruct[] s = new MyStruct[100];
for( int i = 0; i < s.Length; i++ )
{
s[i] = new MyStruct(40, 2);
}

And internally the runtime would have to loop over each piece of memory to run the constructor as well, so there is no real difference between the two - except that the cost is very obvious in the latter example whereas it is less obvious in the first.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway,
although Ollie's answer makes perfectly sense when dealing with
classes, it doesn't seem to me to apply as well if you have to
instantiate an array of structures; consider the following useless
code :

Nov 16 '05 #3

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

Similar topics

4
by: Krzysztof | last post by:
Hi! I have a class: some_class{ private: char* seq; public: some_class(char* se); char* ret_seq(); ....
7
by: Samir | last post by:
<table width="225" border="0"> <tr> <td width="10" id="MyCell1" onclick="ShowHide('MyRow1','MyCell1')"><img src="images/plus3.gif"></td> <td width="205">blahasdfadfadfasd</strong></a></div></td>...
7
by: Lars-Erik Aabech | last post by:
Hi! I've got problems with serializing my collections of business objects. The objects themselves serialize fine, but the collections fail. I've got the following structure: Base collection...
1
by: david | last post by:
I have a question (not sure if just a newbie one, or a stupid one) whose answer I couldn't find on the C# books and tutorials I could put my hands on. Consider the following useless class (could...
5
by: Brad | last post by:
I would like to serialize an arraylist of objects to xml so I can store the xml in a database column. How would I code the serializing and deserializing? Below is a (overly) simple, incomplete...
4
by: Eric A. Johnson | last post by:
For the following code: ' return String representation of CTriangleShape Public Overrides Function ToString() As String ' use MyBase reference to return CShape String Return...
4
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in...
8
by: Lüpher Cypher | last post by:
Hi, Suppose we have a hierarchical class structure that looks something like this: Object | +-- Main | +-- Object1
4
by: pistacchio | last post by:
hi to all! i have the following code (i stripped down the code to a short example, but still it does reproduce the problem): var objs = new Array(); obj = { parameter : " " }
0
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 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
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
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...

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.