CHAPTER 1 THE PHILOSOPHY OF .NET
Given this rule, you can (correctly) infer that the remaining rules of the CLS do not apply to the logic
used to build the inner workings of a .NET type. The only aspects of a type that must conform to the CLS
are the member definitions themselves (i.e., naming conventions, parameters, and return types). The
implementation logic for a member may use any number of non-CLS techniques, as the outside world
won’t know the difference.
To illustrate, the following C# Add() method is not CLS compliant, as the parameters and return
values make use of unsigned data (which is not a requirement of the CLS):
class Calc
{
// Exposed unsigned data is not CLS compliant!
public ulong Add(ulong x, ulong y)
{
return x + y;
}
}
However, if you were to only make use of unsigned data internally in a method, as follows:
class Calc
{
public int Add(int x, int y)
{
// As this ulong variable is only used internally,
// we are still CLS compliant.
ulong temp = 0;
...
return x + y;
}
}
you have still conformed to the rules of the CLS and can rest assured that all .NET languages are able to
invoke the Add() method.
Of course, in addition to Rule 1, the CLS defines numerous other rules. For example, the CLS
describes how a given language must represent text strings, how enumerations should be represented
internally (the base type used for storage), how to define static members, and so forth. Luckily, you don’t
have to commit these rules to memory to be a proficient .NET developer. Again, by and large, an
intimate understanding of the CTS and CLS specifications is typically only of interest to tool/compiler
builders.
Ensuring CLS Compliance
As you will see over the course of this book, C# does define a number of programming constructs that
are not CLS compliant. The good news, however, is that you can instruct the C# compiler to check your
code for CLS compliance using a single .NET attribute.
// Tell the C# compiler to check for CLS compliance.
[assembly: CLSCompliant(true)]
Chapter 15 dives into the details of attribute-based programming. Until then, simply understand
that the [CLSCompliant] attribute will instruct the C# compiler to check each and every line of code
against the rules of the CLS. If any CLS violations are discovered, you receive a compiler error and a
description of the offending code.
20