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 trialJesse Schoonveld
2,943 PointsReally confused about methods and variable scope
So I just finished the c# object track but I feel like I'm completely missing how some key things work. When I follow the videos I feel like I understand it but once I have to do a challenge I feel lost. For example, I never know if I should use void or static when creating a method. Maybe someone could explain it a bit or link me to an explanation.
When I read someone's else's code I can pretty confidently say I can disect wich parts of the code do what. But I find it very hard to make the connections that link these methods together if that makes sense. Like, why is he using a void method here.
1 Answer
Ted Dunn
43,783 PointsStatic and void are actually adressing two different issues.
A static method is a class method which means that you call the method on the class rather than an instance of the class (aka an object). Methods which do not have the keyword static in them are called instance methods for that reason.
For example, say I create a class called Bike and create two different methods: one method has the static keyword in the signature such as public static int countBikes() while the second method has a signature like public int bikeSpeed(). When I wanted to call the countBikes() method I would call it directly on the class like so: Bike.countBikes(). For the second method, I would have to create an instance of the Bike class before I could use the method: Bike aBike = new Bike(), then call the method on the instance/object: aBike.bikeSpeed().
Void is a return type which in the case of void means return nothing. public void singASong() does not return anything after it is executed while public string getFirstName() would return a string after the method finishes execution.
Jesse Schoonveld
2,943 PointsJesse Schoonveld
2,943 PointsThanks, that was a great explanation. I think i get it now at least :)