I am writing a C# class that is exposed 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 doesn't exist. Is there a way I can do this anyway?
EDIT
It turns out there's a SpecialNameAttribute
that lets you declare "special" functions in C# that will allow you (among other things) to overload the VB power operator:
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 class above gets translated by VB into the ^
power operator.
Interestingly, the documentation states the Attribute in not currently used by the .NET framework...
--ORIGINAL ANSWER --
No. The power (^
) operator gets compiled as Math.Pow()
so there's 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
By experiment, it turns out that operator overloading is just syntactic sugar, and better be avoided, if you need to develop in multiple languages. For example, ^
operator of VB.NET gets translated into op_Exponent
function, so this is what's available to you from C#.
Why doesn't C# have a power operator?
You can use a native .NET way so you don't rely on operators:
Math.Pow(x, y);
Also for y=2 it is faster to use multiplication (x*x).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With