views:

30

answers:

1

Hey, I am working on a school project and a line of code I just wrote kind of made me laugh and think to myself, "There must be a better way to do what I just did". So, my question is, is this really the best way to do this? It seems kind of silly. BTW, size is an int that is passed to this function.

 int tiles = Convert.ToInt32(Math.Sqrt(Convert.ToDouble(size)));

I know this works, but is there a better way?

+4  A: 

Since int is implicitly convertable to double, you can leave out the inner conversion:

int tiles = Convert.ToInt32(Math.Sqrt(size));

That being said, Convert.ToInt32 is overkill in this situation. You can also just use a simple cast, since you know it's going from double to int:

int tiles = (int)Math.Sqrt(size);
Reed Copsey
Thanks. I appreciate the response.
PFranchise