Non CLS-Compliant Codes in C#
Common Language Specification (CLS) is set of basic rules and it is expected that a dotnet language must satisfy them. Though C# is probably the biggest language in dotnet framework, it supports many non-CLS-compliant codes mainly to support and maintain the legacy language nativity. Writing C# programs by using only CLS-compliant codes give great portablity among other dot-net programs written in other dotnet langauges. This article tries to list non CLS-compliant codes in C#.
1. Two or more public / protected / protected internal members defined with only case difference
public int intA = 0;
public int INTA = 2;
public int x = 0;
public void X()
{
}
2. Declaring a member name preceding underscore (_) with outside visible access specifiers (public, protected, protected internal)
public void _test()
{
:::::::
}
3. Declaring unsigned type member with access public / protected / protected internal
public uint a = 10;
4. Declaring unsafe (pointer) type with access public / protected / protected internal
protected internal unsafe int *c;
5. A (public / protected / protected internal) method returning a non-CLS compliant type or with parameter of non-CLS compliant type
public uint testmethod(int x, int y)
{
::::::::
}
public void anothermethod(ushort x, int y)
{
::::::::
}
6. An abstract member makred as non-CLS-Compliant in a CLS-Compliant class.
[CLSCompliant(true)]
public abstract class B
{
[CLSCompliant(false)]
protected internal abstract void test();
}
The above codes are not CLS-compliant and one should avoid these type of coding to ensure CLS-Compliant code. Many of CLS are followed by C# and the above list mentioned some of them are not pursued by C#.
There is an attribute, called CLSCompliant, to check whether our code is written in CLS-compliant or not. By giveing CLSCompliant attribute with true parameter, we can get warning message for all non CLS-Compliant codes.
using System;
[assembly: CLSCompliant(true)]
public class Test
{
public static int a = 10;public int intA = 0;
public int INTA = 2;public int x = 0;
public void X()
{
}
protected uint testmethod(int x, int y)
{
return 0;
}
}
[assembly: CLSCompliant(true)] means the CLS-Compliant is enabled to the assembly. After setting this, compiler will check all codes in the assembly for CLS-Compliant and if we want any class or method to not check for CLS-Compliant we can give false for that member alone.
using System;
[assembly: CLSCompliant(true)]
[CLSCompliant(false)]
public class clsA
{
public unsafe int* x;
}public class clsB
{
public unsafe int* x;
}[CLSCompliant(true)]
public class clsC
{
public unsafe int* x;
}
The clsA class will not be checked by compiler for CLS-Compliat but compiler will do for clsB and clsC.



Recent Comments