Google
 

Saturday, June 02, 2007

Using the [assembly: CLSCompliant(true)] attribute in C#

You can apply the CLSCompliant attribute on an assembly (or just about any other program element) and have the compiler check if your code is CLS (Common Language System) compliant (which means it works properly when consumed by other .NET languages). For example, we place the following attribute in all MM .NET AssemblyInfo.cs files:

[assembly: CLSCompliant(true)]

Here are some of the things the compiler checks:

  • Class and member names cannot differ only by case. For example, you can't have one property named Counter and another named counter. This is important for cross-language compatibility since VB .NET isn't case sensitive.
  • Overloaded class methods cannot differ only by out or ref parameter designations.
  • Publicly exposed members cannot start with an underscore ( _ ).
  • Operators can't be overloaded
  • Unsigned types can't be part of the public interface of a class

Unfortunately, although you can apply the CLSCompliant attribute in VB .NET, the VB .NET compiler doesn't check for CLS compliance.

Sample Code:
Note: The exception that is not cls-compliant will not always be thrown and it depends on your compiler settings. If there is no compile exception, a warning will be.
When run the following code in SharpDevelop, both exception and warning will not be thrown.


[CLSCompliant(true)]
public class MyClass
{
public UInt32 Abc() { return 0; }

[CLSCompliant(
false)]
public void abc() { }

private UInt32 ABC() { return 0; }
}


REF:
http://msmvps.com/blogs/kevinmcneish/archive/2004/08/18/12025.aspx
http://www.devarticles.com/c/a/C-Sharp/Making-Your-Code-CLS-Compliant/

No comments: