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

Ikechukwu Arum
Ikechukwu Arum
5,337 Points

The "this" keyword usage is confusing here. The Onmap method takes one parameter of type "Point". Why use "this" here?

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

and then:

namespace TreehouseDefense { class MapLocation : Point { public MapLocation(int x, int y, Map map) : base(x, y) { if(!map.OnMap(this)) { throw new System.Exception(); } } } }

2 Answers

Steven Parker
Steven Parker
221,292 Points

Using "this" is a reference to the current object, in this case a "MapLocation". And since "MapLocation" inherits from "Point", it is valid to use it as an argument to a method that expects a "Point" as a parameter.

The nature of inheritance is that a class that inherits from another can be thought of as a specific kind of the other. So a "MapLocation" is a specific kind of "Point".

Ikechukwu Arum
Ikechukwu Arum
5,337 Points

thanks, but here is my struggle:

using System;

public struct Complex { public int real; public int imaginary;

public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; }

The above code shows the usage of "this" keyword that i understand. i just struggle with applying the same understanding to the MapLocation constructor. I just can't visualize how onMap method goes from accepting a parameter of type Point to accepting the "this" keyword and what that has to do with the x and y parameter(of type int) in the MapLocation constructor. Is there and easier way to explain this to me?

Steven Parker
Steven Parker
221,292 Points

While the "MapLocation" is being constructed, it passes itself (since it is also a "Point") to the "OnMap" method to validate the x and y positions it contains

From the perspective of the "OnMap" method, it only knows that it is being passed a "Point" which it refers to using the parameter name "point". It has no idea that the "this" keyword was used when calling it.

Ikechukwu Arum
Ikechukwu Arum
5,337 Points

thanks Steve, it makes a lot more sense now