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 Using Static Methods

Is using static System.Math good practice? Why does it require static?

I noticed the DistanceTo method uses Math quite a bit, so I tried adding using System.Math at the top to DRY up the code a bit. This resulted in a compile error, and I received a message recommending I add the static keyword.

I now have the line below, which personally find a little easier to parse, but I have two concerns.

return (int)Sqrt(Pow(X - x, 2) + Pow(Y - y, 2));

  1. Is this considered good practice (and does it follow conventions)?
  2. Why does it require the static keyword?

1 Answer

Gonna throw a comment in here, instead of an answer because I am only just learning and might not be the best source of information. I'm sure someone else will be along soon with a better, more accurate answer.

That said, from what I can tell the error is because the using statement is specific to namespaces, which Math is not, so C# gets confused because it thinks you're looking for a namespace called System.Math which doesn't exist. The using static statement is specific to using static classes and their methods, which is is how you can get access to Math and it's methods with using static System.Math. I assume that this would allow you to access the Math class and it's methods even without using the system namespace as well, but I don't know that for sure.

As for good practice, the Stack Exchange posts I looked at didn't say anything about the using static statement being bad form or breaking convention. Also, the Microsoft documentation contains information on it, describing what this statement does and how to use it. I would guess that it is perfectly in keeping with standard conventions, but I am certainly not qualified to give advice on that front so take that guess with a grain of salt.

Anyway, hopefully someone who knows more than me will be along with a proper answer for you shortly.