Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
229,732 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
229,732 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.