Search code examples
c#syntaxusingimport

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.


Solution

  • 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.