More on IL Programming Fundamentals
Now that you know how to write simple programs using IL, let's move ahead writing more examples.
Concatenating Strings
The program in Listing 2 concatenates two strings and displays the result. It differs from the program in Listing 1 only by the symbol + in the ldstr instruction.
Listing 2Concatenation
.assembly welcome{} .assembly extern mscorlib {} .method static public void main() cil managed { .entrypoint .maxstack 1 ldstr "Welcome to .NET Technology Group" + " - PCS" call void [mscorlib]System.Console::WriteLine(class System.String) ret }
Newline Character
Using the newline character \n is the same as that in most languages, such as C/C++, C#, and Java (see Listing 3).
Listing 3Newline Character
.assembly welcome{} .assembly extern mscorlib {} .method static public void main() cil managed { .entrypoint .maxstack 1 ldstr "Welcome to .NET Technology Group\n" + "PCS" call void [mscorlib]System.Console::WriteLine(class System.String) ret }
Declaring a Class and Constructors
Listing 4 shows how to declare a class and constructor using IL. To declare a class we need to use the .class directive. Since a constructor is also a method, it's declared in the same way as that of any other method.
Listing 4Declaring a Class and Constructor
Assembly Name: ILCODE Class Name: NRS Constructor Name: NRS Method Name: main() .assembly ILCODE {} .class public auto ansi NRS extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() il managed { call instance void [mscorlib]System.Object::.ctor() ret } .method public hidebysig static void main() il managed { ldstr "Welcome to .NET Technology Group - PCS" call void [mscorlib]System.Console::WriteLine(class System.String) ret } }
Before moving further let's examine assemblies, manifests, modules, files, attributes, and metadata. Understanding these terms will help you to have good control over the intermediate language.