LordMercury
LordMercury

Reputation: 43

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

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!

Upvotes: 4

Views: 4124

Answers (6)

user4133849
user4133849

Reputation:

variables declared inside a function have a lifetime of the function itself (technically, could be shorter than function itself, due to garbage collector being too smart). What you want is to scope the variable, according to your needs. Which means, it could be scoped to a class instance as a field (i.e. the fields lifetime is not associated to the lifetime of the class instance), or you could scope your variable to be static (i.e. it lives for pretty much entire lifetime of the app, unless you clear or replace the static variable)

Upvotes: 1

user4133778
user4133778

Reputation:

Make the hero variable a field of your class. You can also wrap that field into a Property.

Upvotes: 0

Darren
Darren

Reputation: 70728

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.

Upvotes: 10

AltF4_
AltF4_

Reputation: 2470

If you want to use the hero object outside of this method then you should declare it as global variable outside this method.

Or better even use property to access, set and get the hero object.

I would recommend some further reading on this here: http://www.dotnetperls.com/global-variable

Upvotes: 1

Sybren
Sybren

Reputation: 1079

Declare the player outside of your method on top of your class.

Upvotes: 1

ByoTic
ByoTic

Reputation: 103

When you declare a variable inside a function you can use this variable only inside the function's scope. You have to use a member variable of your class, or to return this player.

Upvotes: 1

Related Questions