
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Writing Code That Is Compatible with the Widest Range of Managed Languages
|
181
The following code shows how to use an instance readonly field:
Foo obj1 = new Foo(100);
Console.WriteLine(obj1.bar);
Those two lines compile into the following IL:
IL_0013: ldc.i4 0xc8
IL_0018: newobj instance void Foo::.ctor(int32)
IL_001d: stloc.1
IL_001e: ldloc.1
IL_001f: ldfld int32 Foo::bar
Since the const field is already compiled into the application as a static member
field, only one simple IL instruction is needed to use this
const field at any point in
the application:
IL_0029: ldc.i4.1
Notice that the compiler compiled away the const field and uses the value it was ini-
tialized to, which is
1. This is faster than using a readonly field. However, const fields
are inflexible as far as versioning is concerned.
See Also
See the “const” and “readonly” keywords in the MSDN documentation.
3.25 Writing Code That Is Compatible with the Widest
Range of Managed Languages
Problem
You need to make sure your C# code will interoperate with all other managed lan-
guages that are CLS-compliant consumers, such as VB.NET.
Solution
Mark the assembly with the CLSCompliantAttribute:
[assembly: CLSCompliantAttribute(true)]
Discussion
By default, your C# assemblies created with VS.NET are not marked with the
CLSCompliantAttribute