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

Jamie Wyton
Jamie Wyton
3,011 Points

this

using the new 'this' command has got me lost a bit. I'm ok with it being used in the MapLocation constructor and that it takes the current object as the argument to be carried over as it calls on the OnMap method. But on the receiving end of OnMap the argument type is Point point! How is this compatible?

1 Answer

andren
andren
28,558 Points

It's compatible because MapLocation is a class that inherits from Point as you can see if you look at it's declaration:

class MapLocation : Point

The : Point means that it inherits from Point. The fact that it inherits from Point means that a MapLocation object can safely be treated as a Point object since it contains all methods and properties that a Point object would have.

Jamie Wyton
Jamie Wyton
3,011 Points

so in the case of the arguments (int x, int y, Map map) - would they then be discarded?

andren
andren
28,558 Points

Any property unique to the MapLocation class would not be accessible while it is being classified as a Point object.

That means map would indeed not be accessible, x and y on the other actually would be. Because those arguments are passed to the Point constructor when the MapLocation object is created.

public MapLocation(int x, int y, Map map) : base(x, y)

The : base(x, y) part of the constructor tells C# to call the constructor of the parent class (Point in this case) with the arguments provided. So x and y are passed to Point which means that those are present even when the object is treated as a Point.

Whenever a class inherits from another class it always has to call the constructor of it's parent to pass it whatever arguments it needs to create a valid instance of that class.

Put as simply as possible MapLocation is a Point object that just has some properties and methods not present in Point, all that happens when it gets treated (cast is the technical term) as a Point object is that those unique properties and methods are no longer accessible. Since MapLocation is guaranteed to have all of the properties and methods that the Point class has it is completely safe to treat it as that object.