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#

I am not sure I understand static fields.

Let me first try to explain what I understand, and hopefully anyone reading can fill in the gaps in my logic. I understand that when we declare a static field, we are only creating one instance of the class regardless of how many times we call the object, its all the same object. In terms of the analogy initially given about how objects can be thought of as tabs on a browser and a class being the layout/template of the tabs, a static field could be thought of as opening the same tab over and over again every time we open a new tab (call a new static field in terms of the analogy) we are opening the same tab over and over again. I understand that this is useful in cases where we might not need multiple instances of an object, for example: we might not need multiple instances of a mathematical formula.

What I am confused about is why are we not using static fields more often in this game, like why is map or path not a static field in for example the game class? Why do we create multiple instances of these classes for every object that calls them? I am not sure what I am missing? Please feel free to explain to me like a child, I will not feel patronized.

1 Answer

A static method can be called without instantiating an object first. Map or point are instantiated - a new instance of that object is created in order for us to manipulate it.

Think of the Console.WriteLine example. This is a static method. You can just call the method without having to instantiate it.