Home   Cover Cover Cover Cover
 

Common Language Specification (CLS)

Example "CLSCompliantAttribute"

The example shows the use of the CLSCompliant attribute.
The first version of our program contains a method the returns a not CLS compliant type.

NotCLSCompliant.cs
using System;

[assembly: CLSCompliant(true)]

public class VisibleType {

  public sbyte Accessible () { return 0; }

}

Because the entire assembly is marked as being CLS compliant, we get an error message from the compiler and no assembly is generated.
>csc /t:library NotCLSCompliant.cs /nologo
NotCLSCompliant.cs(7,9): error CS3002:
	Return type of 'VisibleType.Accessible()' is not CLS-compliant
>dir Not* /b
NotCLSCompliant.cs
In the second version, we explicitly state that the methode Accessible is not CLS compliant and thus avoid that the compiler checks the CLS comliance of this method.

CLSCompliant.cs
using System;

[assembly: CLSCompliant(true)]

public class VisibleType {

  [CLSCompliant(false)]
  public sbyte Accessible () { return 0; }
  
}

Now we do not receive an error message and the compiler generates the assembly (CLSCompliant.dll).
>csc /t:library CLSCompliant.cs /nologo
>dir CLS* /b
CLSCompliant.cs
CLSCompliant.dll