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#

Aaron Selonke
Aaron Selonke
10,323 Points

Object not Instantiated, How can I use its value in the method?

In the C# Objects Video, the teacher creates the OnMap() method inside of the Map Class. I understand how a Point variable can be passed in, and it returns a bool value.

Why can you use the Width and Height values in the method like that? Since the method is written in the Class Map (and I know why he is writing the method) I know that the Width and Height variables in the method are both properties of the Map Class. OK

But they are not instantiated. Since there is not specific object created, they hold no value. I thought that the Class is like the 'Blue Print', even if there was a Map Object(holding a value for Width and Height, how would the method know which instance of Map its referring to?

Sorry if this is a dumb question, working hard to get my head around this concept

namespace TreehouseDefense
{

  class Map
  {

    public readonly int Width;
    public readonly int Height;

    public Map(int width, int height)
    { 
    Width =width;
    Height = height;


    }

    public bool OnMap(Point point)
    {
      return point.X >= 0 && point.X < Width && point.Y >= 0 && point.Y < Height;
    }

  }



}

2 Answers

Steven Parker
Steven Parker
231,236 Points

You're forgetting that these variables are instantiated, along with the class, in the constructor. There will be an object created, and they get values when that happens

Map mymap = new Map(mywidth, myheight);

The method will know which instance holds the values because you must name the instance when you call the method:

isonmap = mymap.OnMap(mypoint);
Aaron Selonke
Aaron Selonke
10,323 Points

Ok, got it (*object).OnMap(object) Thanks