a blog for those who code

Friday 11 December 2015

Building Types into a Module using C# Compiler

In this post we will be discussing about building Types into a Module or File that can be deployed using C# Compiler. In simple terms in this post we will show you how to build a .cs file using C# compiler. C# is a strongly-typed language that means every variable and constant has a type.

C# Compiler uses type information to make sure that all operations that are performed in your code are type safe. Lets take an simple example as shown below :

public class Example {
  public static void Main() {
    System.Console.WriteLine("Hello World");

Above example defines a type, called Example. This type has a method called Main. Inside Main there is a reference of another type called System.Console. System.Console is again a type which is implemented by Microsoft. So the above example defines a type (Example) and uses another company's type.

To build this example, we at first put this code into a file called Example.cs and then build it using the following command which tells the C# Compiler to emit an executable file called Example.exe.

csc.exe /out:Example.exe /t:exe /r:MSCorLib.dll Example.cs

In the above command we have included the /r:MSCorLib.dll (reference to Microsoft DLL) which tells the compiler to look for external types in the assembly identified by the dll. This is done because our code used an external type (System.Console). This is optional because C# compiler automatically references the MSCorLib.dll assembly (as it contains all core types). But if you are using any third party types in your code, you need to add the reference command.

/out:Example.exe and /t:exe are also chose as default by the C# Compiler. So if you use csc.exe Example.cs it will do the same thing.

What exactly is Example.exe file. It is a standard portable executable file. That means if a machine running Windows can be able to load this file and execute it. /t:exe represents Console User Interface, /t:winexe represents Graphical User Interface and /t:appcontainerexe represents Windows Store app.

Note on Reference : When you use the /r: to reference an assembly, you can specify complete path to a particular path. If you do not specify the full path, the compiler will search for the file in the following places Working Directory and the path contains CSC.exe.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment