Sign in to follow this  
brent_w

New to C# - Problem making array of struct.

Recommended Posts

So I've got a strut, lets call it structA, and I want to make an array of structAs. After reading up on C# arrays I tried to do this:
   structA[] structA_Array = new structA[10];
But Visual Studio doesn't like it, not one bit. I've Googled this a few times in attempts of finding the answer, but things I've found seem to imply that this should work. :-\ Could somebody please help a C# newbie out and explain what I've done wrong?

Share this post


Link to post
Share on other sites
Looks good at first glance. My initial guess is that the struct isn't visible to where you're making the declaration.

This for example compiles nicely:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1 {
public struct foo { }
class Program {
static void Main(string[] args) {
foo[] manyFoo = new foo[10];
}
}
}


Share this post


Link to post
Share on other sites
Well I guess my question was phrased incorrectly.

Visual Studio doesn't complain about that line really.
It's just, it doesn't seem to recognize that my array exists - even if I try to use it in the very next line. (It doesn't appear in autocomplete either.)

When I try to place an element into the array:

structA foo = new StructA();
structA_Array[0] = foo;


Visual studio goes straight to the accessor and complains:
Error	1	Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

As if I never declared structA_Array in the first place.

I would have assumed the problem is with my assignment if not for the fact that Visual Studio does not seem to recognize structA_Array's existence at all.

Share this post


Link to post
Share on other sites
Full code? Sounds like a missing semi-colon or something peculiar in the structure.

In my little example program above, you can Console.WriteLine the elements of the array, assign new foo's into it...

Share this post


Link to post
Share on other sites
Quote:
Original post by BlackSeeds
try this:

structA[] structA_Array = new structA[10];

structA_Array[0] = new structA;

structA_Array[0] = foo;

That should work.

Thanks.
I'll give that a try.

But from the looks of it ... does that mean I have to tell C# the type of every array element?
I figured that's what the point of declaring it as an array of structA was for.


Edit:
Nope, that doesn't seem to be my problem.
It still appears to me that VisualStudio is not recognizing the existence of my array.
In both lines it just gave me the same error about declaring an array.

Share this post


Link to post
Share on other sites
It's a bit long what with the XNA code and all, but I suppose you need to see it all to get the context.

Here you go:



using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace _d_Toybox
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class toybox : Microsoft.Xna.Framework.Game
{
/* Start Declarations */
// XNA
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

// Display Settings
float displayWidth;
float displayHeight;

// Item Structure
struct Item_Struct
{
public bool Visible;
public float X_Velocity;
public float Y_Velocity;
public float mass;
public float bouncyness;
public float Width_Factor;
public Texture2D Sprite_Texture;
public Rectangle Sprite_Rectangle;

public void Setup(
bool Vis,
float initalX,
float initalY,
float inital_mass,
float inital_bouncyness,
float displayWidth,
float displayHeight,
float WidthFactor,
Texture2D SpriteTexture)
{
Visible = true;
Sprite_Rectangle.X = (int)(initalX);
Sprite_Rectangle.Y = (int)(initalY);
X_Velocity = 0;
Y_Velocity = 0;
mass = inital_mass;
bouncyness = inital_bouncyness;
Width_Factor = WidthFactor;
Sprite_Texture = SpriteTexture;
Sprite_Rectangle.Width = (int)(displayWidth * Width_Factor);
Sprite_Rectangle.Height = (int)((float)Sprite_Rectangle.Width * ((float)(Sprite_Texture.Height) / (float)(Sprite_Texture.Width)));
}
}

// Array of Item
Item_Struct[] ItemList = new Item_Struct[10];

// Create Items
Item_Struct terra = new objectStruct();
ItemList[0] = terra;

/* End - Declarations */


public toybox()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
displayHeight = graphics.GraphicsDevice.Viewport.Height;
displayWidth = graphics.GraphicsDevice.Viewport.Width;

base.Initialize();
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here

}

/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Get Keyboard State
KeyboardState keys = Keyboard.GetState();

// Check for exit
if (keys.IsKeyDown(Keys.Escape)) { this.Exit(); }


base.Update(gameTime);
}

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.LightSalmon);

// TODO: Add your drawing code here
spriteBatch.Begin();


spriteBatch.End();

base.Draw(gameTime);
}
}
}

Share this post


Link to post
Share on other sites
Quote:
Original post by brent_w
Quote:
Original post by BlackSeeds
try this:

structA[] structA_Array = new structA[10];

structA_Array[0] = new structA;

structA_Array[0] = foo;

That should work.

Thanks.
I'll give that a try.

The code should work, but it shouldn't help. The creation of an array (first line) of structs initializes each item using the default constructor: every field to 0/null. The second line is correct, but it just reinitializes the first element again with the default constructor. The third line then rereinitializes the first element by copying foo's fields.

The error message lets me think you've written something like T x[5];.

Share this post


Link to post
Share on other sites
Quote:
Original post by brent_w
It's a bit long what with the XNA code and all, but I suppose you need to see it all to get the context.

Here you go:



using System;
using System.Collections.Generic;
using More.Stuff;

namespace _d_Toybox
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class toybox : Microsoft.Xna.Framework.Game
{
// snip

// Item Structure
struct Item_Struct
{
/* ... */
}

// Array of Item
Item_Struct[] ItemList = new Item_Struct[10];

// Create Items
Item_Struct terra = new objectStruct();
ItemList[0] = terra;

/* ... */
}
}

The red line is invalid AFAIK. You're not allowed to dump statements into the class itself (i.e. outside a method). I'll go check it to make sure (as I believe java does allow something like that, but C# doesn't...)

Share this post


Link to post
Share on other sites

Item_Struct terra = new objectStruct();
ItemList[0] = terra;



You need to place the assignment in a method. Only declarations (and accompanying initializations) can be declared in a class body like that.

Share this post


Link to post
Share on other sites
Quote:
Original post by Nitage
*** Source Snippet Removed ***

You need to place the assignment in a method. Only declarations (and accompanying initializations) can be declared in a class body like that.


Doh, yeah ... that makes sense.
I feel kinda stupid now that you pointed it out.

That stuff belongs in the initialization method anyways. >.<


Thanks very much for the help.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this