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 trialAllan Oloo
8,054 PointsConstructors and Encapsulation
So here in this tutorial he just calls new constructors new MapLocation
. I thought when using a constructor you have to create an object for example Map map = new MapLocation(arguments)
. In the video he just creates new constructors within the array. I am confused with this part.
try
{
MapLocation[] path = {
new MapLocation(0,2, map),
new MapLocation(1,2, map),
new MapLocation(2,2, map),
new MapLocation(3,2, map),
new MapLocation(4,2, map),
new MapLocation(5,2, map),
new MapLocation(6,2, map),
new MapLocation(7,2, map),
};
}
Also I am confused with encapsulation. I understand the terminology of its use. To hide implementation details and restricts uses of an object. But I don't really understand the meaning of that.
2 Answers
Jon Wood
9,884 PointsFor the constructor, the instructor is using what's called a collection (in this case array) initializer. The C# compiler can infer quite a few things so, by doing this type of initializing, it knows that the type is MapLocation
.
For encapsulation, like you said, it hides implementation details for a more higher level way of using the object. So a user of a library can call a property in that library but it's actually a computed property.
LESTER POLICARPIO
2,139 PointsHi does this mean it can only occur while using collections? and other than collections we should always use
Map map = new MapLocation(arguments)
Jon Wood
9,884 PointsYeah, that type of initializing is mainly done with collections. Even array's have it:
int[] array = {1, 2, 3, 4};
Although, there is also object initializations, which looks similar, but with that you assign the properties to the object instead of each item in a collection.
For example, let's say you have this class:
public class Employee
{
public string Name {get; set;}
public bool IsActive {get; set;}
public DateTime HireDate {get; set;}
}
And in your program, you can use object initialization to create it, like this:
var joe = new Employee
{
Name = "Joe",
IsActive = true,
HireDate = new DateTime(2009, 11, 13)
}
Also, if it helps, there are some good answers on this StackOverflow question. Hope it helps!