GOTCHA #30 Common Language Specification Compliance isn't the defaultWhen I first started learning C#, I heard that it has some C++ features that are not in Java. My first thought was templates. I was quite disappointed to find instead that one of the supported features is operator overloading. It's quite complicated in C++ [Stroustrup00, Cline99]; it gives you many ways to shoot yourself in the foot. Having offered courses on C++ for over 12 years, I know the pain people go through just learning operator overloading. Getting it right is another story [Meyers96, Meyers98]. Overloading is supposed to make your code intuitive and easier to understand, but it often has the opposite effect. Unfortunately, in my opinion, C# took what was complicated in C++ and made it worse. For instance, you can overload the true operator. This requires that you overload the false operator as well. Arbitrarily overloading operators increases the complexity of your code and reduces its readability; its worth is questionable. Furthermore, not all .NET languages support operator overloading. If you write a C# class with overloaded operators, those operators are not accessible from VB.NET. If you have merely overloaded the operators and have not provided equivalent regular methods, your code is not considered to be Common Language Specification (CLS) compliant. CLS compliance requires you to provide a regular method for each overloaded operator.
Consider the example of delegates in .NET. Typically a C# programmer would use the += operator to add or register a delegate. In VB.NET, you can realize the same goal using either the Combine() method or the special AddHandler statement. Similarly, the Remove() method is equivalent to the C# -= operator on delegates. Providing regular methods for each overloaded operator allows users of your class to take advantage of the operators in languages that support overloading, while making it fully usable in languages that don't. If you want your code to be CLS-compliant, then for each operator you must provide a regular method as well. Operator overloading does not reduce the code size. In fact, you will end up writing more methods to accommodate languages that don't support it. IN A NUTSHELLAlways provide a regular method for each overloaded operator. Mark your assembly with the CLSCompliant attribute if you intend to provide language interoperability. Then use the FxCop tool to confirm that you are CLS-compliant. SEE ALSOGotcha #31, "Optional parameters break interoperability." |