C#
  Home arrow C# arrow Making Your Code CLS Compliant
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Making Your Code CLS Compliant
By: Sriram Vaideeswaran
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 51
    2003-08-12

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Best Practices: The Integrated Project and Portfolio Management Platform.

    Hear how IBM Rational Project and Portfolio Management integrated solutions help teams put the right tools and processes in place to maximize the effectiveness and efficiency of project teams and ensure that the business vision is being executed correctly. Learn how to automate and integrate requirements prioritization, top-down project planning, communications and controls, and methodology deployment to keep your scope, costs, and schedules under control. Tackle with an end-to-end approach the management of scope and scope changes, usage of methodology to control and empower project teams, and optimization of resources to align activity costs with the overall project plan.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Don't wait! Try the Rational Application Developer (RAD) v7.5 open beta code today

    Download the Rational Application Developer (RAD) v7.5 open beta code and start developing applications for the JEE5 standard which features EJB3.0, JPA, JSF 1.2, JSP 2.1 and Servlet 2.5 standards. When you use this beta you will see how you can increase developer productivity for already existing applications with improved support for refactoring, as well as adding new features to existing applications. In addition, the beta provides tooling for JD Edwards, Oracle, SAP, Siebel and PeopleSoft to improve the developer productivity with these enterprise systems.
    FREE! Go There Now!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!


    NEW! Cook up Web sites fast with CakePHP, Part 4: Use CakePHP's Session and Request Handler components

    CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    C# ARTICLES

    - Introduction to Objects and Classes in C#, P...
    - Visual C#.NET, Part 1: Introduction to Progr...
    - C# - An Introduction
    - Hotmail Exposed: Access Hotmail using C#
    - Razor Sharp C#
    - Introduction to Objects and Classes in C#
    - Making Your Code CLS Compliant
    - Programming with MySQL and .NET Technologies
    - Socket Programming in C# - Part II
    - Socket Programming in C# - Part I
    - Creational Patterns in C#
    - Type Conversions
    - Creating Custom Delegates and Events in C#
    - Inheritance and Polymorphism
    - Understanding Properties in C#







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek