0

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);

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
  • Sounds like you answered your own question. – Neil N May 28 '12 at 17:15
  • @NeilN i said "overload exponents", not "overload XOR" – Cole Tobin May 28 '12 at 17:16
  • Right, you mean the operator ^. Not exponents themselves, which would be something like Math.Exp – Neil N May 28 '12 at 17:23
  • @NeilN Math.Pow(...). And no, you misread. I added some stuff to the first paragraph for clarification. I want to overload exponents like what Math.Pow(...) does. As Jeffrey said below, some languages use `**`, but C# doesn't have that. – Cole Tobin May 28 '12 at 17:26
  • Yes, I GET what you are saying. You want to overload the operator, not the XOR. But since that operator is already in use for primitives, you can't use it for something else, unless you only apply it to user defined types. – Neil N May 28 '12 at 17:30

2 Answers2

5

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.

Neil N
  • 24,862
  • 16
  • 85
  • 145
1

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.

Jeffrey Sax
  • 10,253
  • 3
  • 29
  • 40