Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an object in c sharp from outside my method?

Tags:

c#

.net

oop

wpf

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!

like image 618
LordMercury Avatar asked Dec 09 '22 06:12

LordMercury


1 Answers

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.

like image 59
Darren Avatar answered Dec 11 '22 07:12

Darren