Recipe 3.25. Writing Code That Is Compatible with the Widest Range of Managed LanguagesproblemYou need to make sure your C# code will interoperate with all other managed languages that are CLS-compliant consumers, such as VB.NET. SolutionMark the assembly with the CLSCompliantAttribute: [assembly: CLSCompliantAttribute(true)] DiscussionBy default, your C# assemblies created with VS.NET are not marked with the CLSCompliantAttribute. This does not mean that the assembly will not work in the managed environment. It means that this assembly may use elements that are not recognized by other CLScompliant languages. For example, unsigned numeric types are not recognized by all managed languages, but they can be used in the C# language. The problem occurs when C# returns an unsigned data type, such as uint, through either a return value or a parameter to a calling component in another language that does not recognize unsigned data typesVB.NET is one example.
Marking your assembly as CLS-compliant means that any CLS-compliant language will be able to seamlessly interoperate with your code; that is, it enables CLS compliance checking. This makes it much easier on developers to catch problems before they manifest themselves, especially in an environment in which multiple managed languages are being used on a single project. Marking your entire assembly to be CLS-compliant is done with the following line of code: [assembly: CLSCompliantAttribute(true)] Sometimes you just can't be 100 percent CLS compliant, but you don't want to have to throw away the benefit of compiler checking for the 99.9 percent of your methods that are CLS compliant just so you can expose one method that is not. To mark these types or members as not being CLS compliant, use the following attribute: [CLSCompliantAttribute(false)] By passing a value of false to this constructor's isCompliant parameter, you prevent any type/member marked as such from causing compiler errors due to non-CLS-compliant code.
The following is a list of some of the things that can be done to make code non-CLS-compliant when using the C# language:
See AlsoSee the "CLSCompliantAttribute Class" topic in the MSDN documentation. |