Akira Midori Akira Midori - 3 months ago 14
C# Question

Getter returns no value

I'm having trouble using setters and getters. When I tried to call a private var from a class to another class, I do not get the value of the var.
Here are some snippets of my code for you guys to check out.

This is my setter getter for the variable.

class PlayerStats

private string _pName;
public string pName
{ get { return _pName; } set { _pName = value; } }
}


This is where I want to show my var.

public void Welcome()
{
PlayerStats pStats = new PlayerStats();
Header();
Console.WriteLine("Hello!");
Console.WriteLine(pStats.pName);

}


This is the method where I inserted a value on my var (this method is executed first before the method welcome)

public void Username()
{
PlayerStats pStats = new PlayerStats();
string name;
Header();
Console.Write("\nChoose your USERNAME: ");
name = Console.ReadLine();
pStats.pName = name;
}


None of this are running from the main method. I thought of doing my program by just calling out different methods from different classes in the main method so it kinda looks like this:

static void Main(string[] args)
{
Jobs jobCl = new Jobs();
GUI gui = new GUI();
gui.Header();
gui.StartPage();
gui.Username();
gui.ChoosepJob();
gui.Welcome();
Console.ReadLine();
}


When I call the var from the username method, I have no problem printing it but I cant make it to print if I am to call it from other methods.

Thank you for any help you can provide. Also if you can suggest a different way of doing this, please don't hesitate to say it to me

Answer

Don't make a new PlayerStats every method, make it once outside of the methods then pass it in to each one. You likely have the same problem with Jobs and that likely needs to be passed in to ChoosepJob

static void Main(string[] args)
{
    PlayerStats pStats = new PlayerStats();
    Jobs jobCl = new Jobs();
    GUI gui = new GUI();
    gui.Header();
    gui.StartPage();
    gui.Username(pStats);
    gui.ChoosepJob(jobCl);
    gui.Welcome(pStats);
    Console.ReadLine();
}

public void Welcome(PlayerStats pStats)
{
    Header();
    Console.WriteLine("Hello!");
    Console.WriteLine(pStats.pName);

}

public void Username(PlayerStats pStats)
{
    string name;
    Header();
    Console.Write("\nChoose your USERNAME: ");
    name = Console.ReadLine();
    pStats.pName = name;
}