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 Methods Overloading Methods

Ranvir Sahota
Ranvir Sahota
9,844 Points

Why Overload DistanceTo?

I understand that one of the benefits to, overloading methods allows the program to handle multiple data types passed through. However, I still don't see the point in overloading DistanceTo? Can someone explain why we did this? Thanks!

1 Answer

It's not exactly necessary to do so, but it does make things easier when dealing with data that can take on different forms. In the case of DistanceTo, I would assume that you can call it by passing individual values for x and y in one version and then overload DistanceTo in a way that would take an object (x, y) as a singular value. Some functions in C# handle packed data objects better for some things, while others can only process individual values for floats, ints, and so on. Since we don't know what data we're going to be messing with, creating a simple overload that unpacks or packs the data from or to an object is a nice way to handle both scenarios with relative ease. It's one of those "set it and forget it" sort of things that you don't usually notice in small applications, but that will go a long way to making our jobs easier later on in projects that are thousands or even millions of lines of code. Whenever you're processing and manipulating data that can appear in more than one form, it's always a good idea to create the overload early on as a sort of failsafe, just in case you hit a point where you, for example, have no choice but to use that Vector2(x, y) point for that really handy, quite specific, built-in math function but you need x1 - x2 and y1 - y2 for other parts.