Introduction

Sometimes there is a need for code written in one language to access another language, but programming languages that target CLR are different from one other, for example C# is case sensitive but VB is not. This can cause a problem when we access code written in one language from another language. So .Net has come up with CLS; i.e., Common Language Specification.

Definition

CLS defines a minimum set of features that must be supported by all languages that target CLR.

Figure - The below Venn diagram will be helpful to understand CLS.
CLR/CTS supports lots of feature but that does not mean all the languages that target CLR supports all these feature.
As per the above Venn diagram:
  • CLR is a superset of all languages that target CLR.
  • C# and VB are subsets of CLR
  • CLS is a minimal subset that is a must-have for all languages targeting CLR.
  • Also some of the features are common in C# and VB other than CLS features.
CLSCompliant Attribute

Before starting with any concrete program/example on CLS, I will explain a useful attrubute that needs to be included while writing CLS Compliant Code.

Syntax : [assembly:CLSCompliant(true)]

If you set CLSCompliant attribute to true, it gives a compile time warning if you write any public or protected member which is not CLSCompliant. It will give a warning for only public and protected members, not for private, as private members can be accessed only within that class.

Example 1

C# is case sensitive but VB is not; that's why public members that differ by case will give you a warning.
  1. using System;
  2. [assembly: CLSCompliant(true)]
  3. namespace CLSExamples
  4. {
  5. public class CaseSensitiveExample
  6. {
  7. static void Main(string[] args)
  8. {
  9. }
  10. public void XYZ()
  11. {
  12. Console.WriteLine("Inside XYZ");
  13. }
  14. public void Xyz()
  15. {
  16. Console.WriteLine("Inside Xyz");
  17. }
  18. }
  19. }
Upon execution of the above code you will get a warning as :Identifier 'CaseSensitiveExample.Xyz()' differing only in case is not CLS-compliant.

Example 2

C# supports Unsigned Integer but VB does not support Unsigned Integer
  1. using System;
  2. [assembly: CLSCompliant(true)]
  3. namespace CLSExamples
  4. {
  5. public class OptionalParameterExample
  6. {
  7. static void Main(string[] args)
  8. {
  9. }
  10. public UInt32 XYZ(int a)
  11. {
  12. Console.WriteLine("Inside XYZ");
  13. return (UInt32)(a * a);
  14. }
  15. }
  16. }
Upon compilation the above code will give a warning as: Return type of 'OptionalParameterExample.XYZ(int)' is not CLS-compliant.

Note
  1. There can be many language specific features that are not CLSCompliant. To help you understand, I have used the above examples.
  2. Above code snippets are tested and working.
G
M
T
Text-to-speech function is limited to 200 characters