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 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
229,608 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
229,608 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