Interacting with overloaded operators from overloaded operator challenged languages

Interacting with overloaded operators from overloaded operator challenged languages

  • Comments 3

Like the C++ language, C# allows you to overload operators for your custom types. For example, assume you have a structure named MyPoint which has overloaded the plus operator. If this is the case, you can 'add' two MyPoints as so:

// Add two MyPoint types to obtain a 
// 'bigger' Point.
MyPoint bigPoint = ptOne + ptTwo;

Although this is a very powerful technique, many C# programmers avoid doing so in fear of building non CLS-compliant types. Fear not! Every overloaded operator maps to a 'special' static CIL method which can be invoked by languages which do not natively support directly operator manipulation. In our case, 'operator +' maps to a method named 'op_Addition()'. Given this, a VB.NET programmer could interact with MyPoint as so:

' Add two MyPoint types to obtain a 
' 'bigger' Point.
Dim bigPoint as MyPoint = _
  MyPoint.op_Addition(ptOne + ptTwo)

Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003

Leave a Comment
  • Please add 5 and 4 and type the answer here:
  • Post