VB.Net Power operator (^) overload with C #

I am writing a C # class that is open to VB.Net. I would like to overload the vb.net ^ operator so that I can write:

 Dim c as MyClass Set c = New ... Dim d as MyClass Set d = c^2 

In C #, the ^ operator is the xor operator, and the power operator does not exist. Is there a way I can do this?

+5
source share
2 answers

EDIT

It turns out there is SpecialNameAttribute , which allows you to declare "special" functions in C # that will allow you (among other things) to overload the VB power statement:

 public class ExponentClass { public double Value { get; set; } [System.Runtime.CompilerServices.SpecialName] public static ExponentClass op_Exponent(ExponentClass o1, ExponentClass o2) { return new ExponentClass { Value = Math.Pow(o1.Value, o2.Value) }; } } 

The op_Exponent function in the above class translates VB into the power operator ^ .

Interestingly, the documentation indicates an attribute that is not currently used by the .NET platform ...

- ORIGINAL RESPONSE -

Not. The power ( ^ ) operator Math.Pow() as Math.Pow() , so there is no way to "overload" it in C #.

From LinqPad:

 Sub Main Dim i as Integer Dim j as Integer j = Integer.Parse("6") i = (5^j) i.Dump() End Sub 

IL:

 IL_0001: ldstr "6" IL_0006: call System.Int32.Parse IL_000B: stloc.1 IL_000C: ldc.r8 00 00 00 00 00 00 14 40 IL_0015: ldloc.1 IL_0016: conv.r8 IL_0017: call System.Math.Pow IL_001C: call System.Math.Round IL_0021: conv.ovf.i4 IL_0022: stloc.0 IL_0023: ldloc.0 IL_0024: call LINQPad.Extensions.Dump 
+9
source

In an experiment, it turns out that operator overloading is just syntactic sugar, and is best avoided if you need to develop in multiple languages. For example, the ^ VB.NET operator is translated into the op_Exponent function, so this is what is available to you from C #.

Why doesn't C # have a power operator?

You can use your own .NET method to not rely on operators:

 Math.Pow(x, y); 

Also for y = 2 it is faster to use multiplication (x * x).

+2
source

All Articles