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.
- using System;
-
- [assembly: CLSCompliant(true)]
- namespace CLSExamples
- {
-
- public class CaseSensitiveExample
- {
- static void Main(string[] args)
- {
-
- }
-
- public void XYZ()
- {
- Console.WriteLine("Inside XYZ");
- }
- public void Xyz()
- {
- Console.WriteLine("Inside Xyz");
- }
- }
- }
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
- using System;
-
- [assembly: CLSCompliant(true)]
- namespace CLSExamples
- {
-
- public class OptionalParameterExample
- {
- static void Main(string[] args)
- {
-
- }
-
- public UInt32 XYZ(int a)
- {
- Console.WriteLine("Inside XYZ");
- return (UInt32)(a * a);
- }
- }
- }
Upon compilation the above code will give a warning as: Return type of 'OptionalParameterExample.XYZ(int)' is not CLS-compliant.
Note
- There can be many language specific features that are not CLSCompliant. To help you understand, I have used the above examples.
- Above code snippets are tested and working.
| | | | | | | | | |
Text-to-speech function is limited to 200 characters
| | | | | | | | | |
Text-to-speech function is limited to 200 characters