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 trialRoberto Rodriguez
1,446 PointsClass 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
231,248 PointsIf 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.
Roberto Rodriguez
1,446 PointsOH OK, I get it now. I see what you mean. That helps a lot. Thanks! You were of great help.
Roberto Rodriguez
1,446 PointsRoberto Rodriguez
1,446 PointsSo 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
231,248 PointsSteven Parker
231,248 PointsUse the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. 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).