Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C#

Class Instances and Methods

My biggest question about this is how I can keep an instance of a class consistent with many methods and more to them. Like if I make a player instance of a class and call it Tim in the main method, how would I be able to use that same Tim instance in a different method?

2 Answers

Steven Parker
Steven Parker
215,958 Points

If you create an instance of another class in a variable of your current class, any method of the current class would have access to it. Just be sure to use a class variable and not a local variable of the method that creates it.

So it would work if I do something like this: class Program { class Person { public string name = "Tim"; public int age; }

public static void Main() { Person tim = new Person tim.name = "Tim"; }

public static void OtherMethod() { tim.age = 7; } }

sorry if this is messy, but this would work? The instance of the Person class can be carried into two different methods? And thank you for the response And after posting this I see how much a mess this is but sorry I don't have a better way of asking. Thanks if you can decipher and help me on this

Steven Parker
Steven Parker
215,958 Points

Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

But the problem here is that you're creating a local variable in the "Main" method. You need to create it as a class variable instead (inside the class, but not inside any method).

class Program
{
    class Person
    {
        public string name = "Tim";
        public int age;
    }

    static Person tim;       // declare at class level

    public static void Main()
    {
        tim = new Person();  // but you may INITIALIZE in the method
        tim.name = "Tim";
    }

    public static void OtherMethod()
    {
        tim.age = 7;
    }
}

OH OK, I get it now. I see what you mean. That helps a lot. Thanks! You were of great help.