Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,133 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