Reputation: 9429
Is there a way to overload exponents in C#? I know in some languages (can't name any off the top of my head), ^
is used for exponential functions, but in C++ and C#, ^
is the bitwise XOR operator, which can be overloaded, but this is not what I want to overload. I wan't to overload the power function or whatever
For example. I know I can do 2^x
with (1 << x)
. So, my second part, is there an exponential operator in C# or do I have to stick with System.Math.Pow(base, exp);
Upvotes: 0
Views: 1667
Reputation: 25258
You could create an extension method to act as a shortcut to Math.Pow(), this is actually a vey common thing to do.
perhaps:
public static double Pow(this double a, double b)
{
return Math.Pow(a, b);
}
So then you can use it like this:
myDouble = myDouble.Pow(3);
There's various formats you can play around with when it comes to extension methods. If your goal is brevity, I'm sure you can come up with something you'll be happy with.
Upvotes: 5
Reputation: 10323
Basic dialects and Matlab use ^
for the exponent operator. Other languages (Fortran, Python, F#) use **
. C# unfortunately doesn't have an exponent operator.
Although it is possible to overload the ^
XOR operator in C#, it is not recommended since it would be confusing to have an operator with an unusual and undocumented meaning.
Even then, overloading is only possible if either or both of the base and the exponent operands are of a user-defined type. You can't just define '^' to mean exponentiation for, say, doubles.
Upvotes: 1