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 trialDaniel Sanchez
1,748 Pointsusing a method problem
I dont understand entirely when you are using a method, in this example, the teacher is using the DistanceTo method in the game class by putting:
Point point = new Point(4,2); Console.WriteLine(point.DistanceTo(5,5));
In here, I understand that is pritning the distance that is between the point variable that he created and another point that he is specifying inside the parenthesis, but when he uses the OnMap method:
Map map = new Map(8,5); map.Onmap(new MapLocation(0,0));
I dont undersatnd inside of the OnMap parenthesis how he is using the MapLocation method, he just put the keyword "new"... how does that work? Is not supposed to create a variable before and then use it?
2 Answers
andren
28,558 PointsThe OnMap
method expects you to pass it an instance of the MapLocation
class, you create an instance of a class by typing new
followed by the class' constructor, which is MapLocation()
in this case.
Instances are often stored in variables but they don't have to be. As far as C# is concerned they are just a type of value, just like a string
or an int
. And just like you can pass those directly as arguments (like is done in your first example) you can pass the MapLocation
instance directly as well.
Variables and the value they contain are interchangeable, so if you can use a variable for some purpose then you can also use the raw value in the same place without issue. Variables are generally only necessary when you want to store a value for use later in your code, or in instances where you are going to use the same value in multiple places.
Which means that you could have stored it in a variable like this:
MapLocation mapLocation = new MapLocation(0,0);
Map map = new Map(8,5);
map.OnMap(mapLocation);
And it would have worked exactly the same as it did without a variable, but since the MapLocation
you create is only going to be used once, storing it for later use is not really necessary.
Daniel Sanchez
1,748 PointsOhhh, I understand a lot better now, thanks a lot andren!!! you are the best