Skip to main content
GameDev.net gamedev.net
🔒 Locked

[C#] Non-default constructor, struct, array.

Started by Thevenin Dec 23, 2005 at 1:44 AM 2 replies 800+ views
Original Post
Thevenin
Thevenin
I have a struct like so...
struct ABox
{
     int TheRadius;
     public ABox(bool TheLogic)
     {
          TheRadius = TheLogic ? -1 : 0;
     }
}
And I'm trying to make an array of these boxes (all using the constructor). I tried this... ABox[] TheCircularBoxes = new ABox(true)[1000]; ... but C# doesn't like it. How do I do it?
Thevenin
Thevenin
Hum.. given the fact that my structs(Not the one shown above) are quite large (structs are stored on the stack, and passed by value), I wonder if it would be better to just use a class.

Humm... de... dum.. dum... deee....

Class it is.
Thevenin
Thevenin
Just out of curiosity, was the answer this...

ABox[] TheCircularBoxes = new ABox[1000];for(int TheLoop=0;TheLoop < TheCircularBoxes.Length;TheLoop++)     TheCircularBoxes[TheLoop] = new ABox(true);


... cause somehow it just feels soo wrong to do it this way. =/
mikeman
mikeman
It's not wrong. C# arrays are objects that contain N elements of either value or reference types. A struct is a value type, a class is a reference type. When you declare:

Obj[] Arr = new Obj[1000];

you create an Array that contains 1000 elements.

If Obj is a reference type(class), you don't have 1000 instances of type Obj. You just have 1000 object references, that are currently initialized to null. If you try to use it, you will get an error "object reference not set to an instance". You must initialize all references just as you mentioned in that piece of code.

If Obj is a value type(struct), you will have 1000 instances of type Obj, with all members initialized to zero. Again, the code you posted is correct, since new is the only way to call a struct constructor besides the default parameterless one(which you can't define yourself).

[Edited by - mikeman on December 23, 2005 5:51:43 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.