Is your C# code in line with the .NET Command Language Specification (CLS)? In this article, Sriram shows us how to check and fix our code for compliance. Introduction
If you are writing .Net classes, which will be used by other .Net classes irrespective of the language they are implemented, then your code should conform to the CLS [Common Language Specification]. This means that your class should only expose features that are common across all .Net languages. The following are the basic rules that should be followed when writing a CLS complaint C# code.
1. Unsigned types should not be part of the public interface of the class. What this means is public fields should not have unsigned types like uint or ulong, public methods should not return unsigned types, parameters passed to public function should not have unsigned types. However unsigned types can be part of private members.
2. Unsafe types like pointers should not be used with public members. However they can be used with private members.
3. Class names and member names should not differ only based on their case. For example we cannot have two methods named MyMethod and MYMETHOD.
4. Only properties and methods may be overloaded, Operators should not be overloaded.
The above-mentioned rules should be followed only for the types and member that are publicly exposed by your program. Private classes, private methods and local variables need to follow the rules.
By default the C# complier does not check for CLS compliance of the code. We should explicitly make the C# compiler check for CLS compliance by using the CLSCompliantAttribute class. By specifying the value of true to this attribute we specify that the C# compiler should check for the CLS compliance of the code. The CLSCompliantAttribute can be applied to assemblies, modules, types, and members.
For marking an entire assembly as CLS compliant the following syntax is used
using System; [assembly:CLSCompliant(true)]
For marking a particular method as CLS compliant the following syntax is used
[CLSCompliant(true)] public void MyMethod()
If you mark an assembly as CLSCompliant and if any of the publicly exposed types of members are not CLS compliant then the compiler would raise an error as shown in the following example.
Example
using System; //setting CLSCompliant attribute to true [assembly:CLSCompliant(true)] [CLSCompliant(true)] public class Test { public void MyMethod() { } //error because methods differ only in their case public void MYMETHOD() { } static void Main() { } }
Compiling the above code will result in the following error:
error CS3005: Identifier 'Test.MYMETHOD()' differing only in case is not CLS-compliant
A program section cannot be marked as CLScompliant if the section, which encloses it, is not marked as CLScompliant. For example, a class cannot be marked as CLSCompliant if the assembly is not marked for CLScompliant.
Example
using System; //setting CLSCompliant attribute to true [CLSCompliant(true)] public class Test { public void MyMethod() { } //error because methods differ only in their case public void MYMETHOD() { } static void Main() { } }
Compiling the above code will result in the following error:
'Test' cannot be marked as CLS compliant because the assembly is not marked as compliant
You can also mark particular section of a CLS compliant class as non-CLS compliant by setting the CLSCompliantAttribute to false for the particular section. The compiler will not enforce CLS compliance for sections, which are marked as non-CLS compliant.
Example
using System; //setting CLSCompliant attribute to true [assembly:CLSCompliant(true)] [CLSCompliant(true)] public class Test { public void MyMethod() { } //Not an error because the methods is not CLS complaint [CLSCompliant(false)] public void MYMETHOD() { } static void Main() { } }
Compiling the above code will not result in an error, as the method is marked as non-CLS compliant.
Following are the some situations which may cause the C# compiler to raise an error
1. If your class methods that are identical but differ only by ‘out’ or ‘ref’.
2. If a publicly exposed member starts with an underscore (_).
3. If an abstract member is marked for non-CLS compliance within a CLS compliant class.
Conclusion
If you develop applications that conform to the CLS, your program will be interoperable with a wide range of .Net supported programming languages. Therefore, your application is likely to have a wider customer base than a non-CLS-compliant version of your application. You can make sure that the C# programs you develop are CLS compliant by using the CLSCompliantAttribute, which will cause the compiler to raise errors if the program is not CLS compliant.| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More C# Articles More By Sriram Vaideeswaran developerWorks - FREE Tools! | <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts. FREE! Go There Now!
| | | | Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success. FREE! Go There Now!
| | | | Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
| | | | This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer. FREE! Go There Now!
| | | | Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications. FREE! Go There Now!
| | | | Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications. FREE! Go There Now!
| | | | IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects. FREE! Go There Now!
| | | | Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available. FREE! Go There Now!
| | | | This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”. FREE! Go There Now!
| | | | Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs). FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |