I am a novice programmer and i need some help understanding what is wrong. I create an object in which constructor's I create my players. However as soon as I finish my constructor all objects craeted inside the other are null. Is it not possible for an object to create objects? if not how can I design my program so I can access my player objects from any class.?
class Program
{
static void Main(string[] args)
{
Tablero tablero = new Tablero();
tablero.test(); //now Tablero doesnt have player
Console.ReadLine();
}
public class Tablero
{
Buscador busc1;
public Tablero()
{
Buscador busc1 = new Buscador(50);
//test(); same problem
}
public void test()
{
Console.Write(busc1.getPosX());
}
}
public class Buscador
{
int posx;
public Buscador(int posx)
{
this.posx = posx;
}
public int getPosX()
{
return posx;
}
}
}
You have defined Buscador busc1; in the main body of the class so instead of:
Buscador busc1 = new Buscador(50);
simply write
busc1 = new Buscador(50);
By doing the first one, you are saying that you want to create an instance of Buscador local to the method instantiating it. Therefore, it is removed once the method ends and is not accessible from any other methods.
Buscador busc1; defined outside of the Tablero() constructor is accessible to any methods in the entire class.
See this MSDN article about scoping:
http://msdn.microsoft.com/en-us/library/ms973875.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With