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: 4 stars4 stars4 stars4 stars4 stars / 50
    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! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    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!


    NEW! Download a free trial of WebSphere Business Modeler Advanced V6.1.1

    Visit IBM developerWorks to download a free trial version of WebSphere Business Modeler Advanced V6.1.1, IBM’s premier business process modeling and analysis tool for business users that offers process modeling, simulation, and analysis capabilities. IBM WebSphere Business Modeler helps you visualize, understand, and document business processes for continuous improvement.
    FREE! Go There Now!


    NEW! Harnessing the power of SQL and Java for high performance data access

    Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    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!


    NEW! Rational Talks to You:Per Kroll on Rational Method Composer Plug-in customization

    Join this Rational Talks to You teleconference on December 11 at 1:00 pm ET to get tips on building your own plugins with Rational Method Composer. Get your questions answered!
    FREE! Go There Now!


    NEW! Run your first CICS application on a PC using TXSeries for Windows

    Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1.
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    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!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    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 4 hosted by Hostway
    Stay green...Green IT