I'm completely new to C#, WPF and OOP, and am facing a problem with objects.
I'm creating a small RPG and have a Player class that has a constructor automatically assigning default values to the instanciated object.
So with WPF/XAML, I created a button that is linked to a function; when I Press the button, this function will be executed:
private void NewGameClick(object sender, RoutedEventArgs e)
{
Player hero = new Player("Tristan");
MessageBox.Show("The character " + hero.Name + " has been created.");
}
The message box indeed shows the name of the character, but I can't use the "hero" object created by the function in the rest of my code. Is it because the object is deleted at the end of the function? Is there any way to keep that object and use it outside of that function?
Thanks!
The hero
object only exists inside the NewGameClick method and will go out of scope after the method has finished executing.
You can declare your object outside of the method and it will be in the scope of that class. For instance.
public class Game
{
Player hero = new Player("Tristan");
private void NewGameClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("The character " + hero.Name + " has been created.");
}
}
You then have a private
Player object inside the Game class
to work with.
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