C# FAQ: How call overloaded operators from non-supporting languages

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How call overloaded operators from non-supporting languages?

In C# as in C++, operators can be overloaded to handle custom types. For example, assume a structure named BigPoint which features an overloaded plus (+) operator allowing the "addition" of two BigPoint objects as follows:

// Add two BigPoint types to obtain a 'larger' Point.
 
BigPoint largePoint = pointOne + pointTwo;

Many C# developers avoid this powerful technique for fear of building non-CLS-compliant types. But, there is no reason to fear compatibility. Every overloaded operator maps to a special static CIL method which is invocable by languages without native support for operator manipulation.

In this example, operator + maps to a method named op_Addition(). So, a Visual Basic .NET programmer could interact with BigPoint like this:

' Add two BigPoint types to obtain a 'larger' Point.
 
Dim largePoint as BigPoint = _
   BigPoint.op_Addition (pointOne + pointTwo)

MSDN references



Personal tools