Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Math references be shortened in C#?

In VB.NET, I could make my math code a lot cleaner by Importing System.Math and referencing its methods directly:

Imports System.Math
[...]
Return New Vector3(Sin(az) * Cos(el), Cos(az) * Cos(el), Sin(el))

But I don't think C# can Use classes in order to access their methods implicitly, so I have to do something like:

using System;
[...]
return new Vector3(Math.Sin(az) * Math.Cos(el), Math.Cos(az) * Math.Cos(el), Math.Sin(el));

But that's ugly; it needs its own scroll bar!. Is there any way to write something in C# that looks like my VB.NET code? I could write local wrapper methods for Sin and Cos, but wouldn't that reduce performance (because of the overhead of function calls)? And, that would require writing wrapper functions for every Math function I'm using in every class I'm using them in; that's not so desirable either.

like image 514
Ben Avatar asked Jun 19 '12 19:06

Ben


2 Answers

You could give System.Math an alias with the using directive:

using M = System.Math;

return new Vector3(M.Sin(az) * M.Cos(el), M.Cos(az) * M.Cos(el), M.Sin(el));

That's the best I got.

I could write local wrapper methods for Sin and Cos, but wouldn't that reduce performance (because of the overhead of function calls)?

You could, and at that point you could use generics and other niceties to make it even more convenient, but you would still be referencing a library like this, unless all the math was happening in the same class where this code is occuring as methods.

The question of "performance from overhead" is answered with "additional stack frames for something this simple are non-noticeable for standard applications". If you were in a tight loop, then yes, that would be an issue.

like image 88
jcolebrand Avatar answered Oct 24 '22 21:10

jcolebrand


As of C# 6.0 you can shorten the math references by adding a using static declaration:

using static System.Math;

This allows you to use static members of the Math type without qualifying it with the type name:

public void Foo()
{
     var bar = Sin(8);
}

There is no way to do this "globally" since there is no way to apply a using declaration globally at all, currently.

For those not using C# 6

but wouldn't that reduce performance (because of the overhead of function calls)?

I wouldn't worry about it. Write your code to be readable first. We can write the method a few different ways. The first, is to just add white space:

return new Vector3(
    Math.Sin(az) * Math.Cos(el),
    Math.Cos(az) * Math.Cos(el),
    Math.Sin(el)
);

You can also put that in a helper method, too.

jcolebrand's answer is a nice was of doing that too, but it requires adding a using m = System.Math; everywhere.

like image 32
vcsjones Avatar answered Oct 24 '22 19:10

vcsjones