I am relatively new to c# and am making a 2D physics engine as a fun project to learn the language and the .NET environment.

I am making a form that can be used to modify the number of objects. Unfortunately, I cannot find a way to change the length of the array passed to the form via its constructor.
I suppose "ref" would work except that the length is actually modified in another method besides the constructor.
Some combination of "unsafe" and "fixed" might also have worked if they could be made to have scope outside the constructor method of this form's class.

I want to do something like the pseudo code below:

//When appropriate menu item clicked, create an instance of the "new ball creation" form:
AddBallClass NewBallWindow = new AddBallClass(ref BallArray, MouseClickPos.X,MouseClickPos.Y);
NewBallWindow .Show();

//code found in the "AddBallClass" form:
public class AddBallClass: Form{
...
	private Ball[] *PointerToBallArray;
	private int PosX,PosY,length;
	private Ball[] NewBalls;
...
	public AddBallClass(ref Ball[] Balls, int x, int y){
      		PointerToBallArray=&Balls[];
		PosX=x;
		PosY=y;
		length=Balls.Length();
		NewBalls = new Ball[length+1];
		Balls.Copy(NewBalls);	
	}
...
	private void OKbutton_Click(object sender, EventArgs e)
        {
		*PointerToBallArray = new Ball[length+1];//increasing the size of the original array, to make room for the new ball
		NewBalls.Copy(*PointerToBallArray);//copy the new ball list data to the original.
        }
}

Thanks,
Dustin

Recommended Answers

All 3 Replies

Seems like you are trying to make your life extremely difficult.
Don't know what you are trying to do, but why not use the features of C#? Use a generic list of balls.

class Ball{//..code here}

List<Ball> MyBallList = new List<Ball>();

Now with MyBallList you can add, remove, insert and never worry about pointers, or arraylength any more.
See this

commented: Generics are the way to go! :) +14

Generic lists ended up being useful elsewhere. thanks for the hint.

I probably should have figured out a way to make my post shorter. What I needed was a way to re-size the array. Even though arrays are passed by reference, "new" acts on the local variable, not the one being referenced.

However, I did find a decent workaround. Maybe I'll look more into this later...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.