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 trialGraham Atlee
3,907 PointsWhy use a constructor?
When filling in a class, why initialize the fields inside a constructor when I can just initialize the fields with the desired value at declaration.
example:
public readonly int Width = 8; public readonly int Height = 5;
1 Answer
andren
28,558 PointsIf you set Width
and Height
outside of the constructor then there would be no way of customizing the map when you instantiate it. Let's say I wanted to have multiple stages in the game, each one having a different map. With the code in the video I could simply create three different Map
objects with different numbers passed in to the constructor. Like this for example:
Map smallMap = new Map(4, 4);
Map mediumMap = new Map(8, 8);
Map bigMap = new Map(12, 12);
With your code that would not work since the Map
class would be hardcoded to always be the same size. Generally speaking a fixed value class tends to be far less useful than one that can be customized to be useful in multiple scenarios.
Also in many cases you won't actually know what the desired value is while coding the class. For example if I decided to make it possible for the player to type in the map size themselves.