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# C# Objects Inheritance Catching Exceptions

Compiler error regarding my static/instance methods of the OnMap method

I have been following this course, and I just got to this point, where it asks me to run the "OnMap" method, which the code apparently has deemed unusable, as it is a "non-static" method. I then change it to static, but this only grows more errors, which I then patch and mount more errors. Is there any suggestion that one could give to help solve this conundrum?

for reference, here is the code that I have used, and the error message upon compiling: error:

MapLocation.cs(5,16): error CS0120: An object reference is required to access non-static member `TreehouseDefense.Map.OnMap(TreehouseDefense.Point)'

MapLocation.Cs:

namespace TreehouseDefense{
  class MapLocation : Point {
    public MapLocation(int x, int y, Map map) : base(x, y){
      if (!Map.OnMap(this) ) {
          throw new OutOfBoundsException(x + "," + y + " is out of bounds");
        }
    }
  }
}

Map.OnMap():

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

2 Answers

Jon Wood
Jon Wood
9,884 Points

Just a guess from looking at the code, maybe this line: if (!Map.OnMap(this) ) should use the map variable that was from the constructor. So it'd be like this: if (!map.OnMap(this) ).

Hope it helps, but let me know if it doesn't work.

Ah, alrighty then. I think from now on I'm just gonna ignore the suggestion to name objects and methods the exact same thing, just so that I don't have to run into this kind of error again. This would be far too difficult to spot later on down the line.

Thank you for catching my mistake here.

Christopher Debove
Christopher Debove
Courses Plus Student 18,373 Points

If you want to you can. But later on it will almost always be the case. Coding like this and finding these mistakes will help you to be more confortable with it =)