Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Your First Application: Take One

With the .NET Framework installation in place, we’re ready to develop our first .NET application. But wait a minute... where are the development tools to make our lives easy? That’s right, for just this once, we’ll lead a life without development tools and go the hardcore route of Notepad-type editors and command-line compilation to illustrate that .NET development is not tightly bound to the use of specific tools like Visual Studio 2012. Later in this chapter, we get our feet back on the ground and explore the Visual Studio 2012 tooling support, which will become your habitat as a .NET developer moving forward.

So as not to complicate matters, let’s stick with a simple command-line console application for now. Most likely, the majority of the applications you’ll write will either be GUI applications or web applications, but console applications form a great ground for experimentation and prototyping.

Our workflow for building this first application is as follows:

  • Writing the code using Notepad
  • Using the C# command-line compiler to compile it
  • Running the resulting program

Writing the Code

Clichés need to be honored from time to time, so what’s better than starting with a good old Hello World program? Okay, let’s make it a little more complicated by making a generalized Hello program, asking for the user’s name to show a personalized greeting message.

Open up Notepad, enter the following code, and save it to a file called Hello.cs:

using System;

class Program
    static void Main()
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        Console.WriteLine("Hello " + name);

Make sure to respect the case of letters: C# is a case-sensitive language. In particular, if you come from a Java or C/C++ background, be sure to spell Main with a capital M. Without delving too deeply into the specifics of the language just yet, let’s go over the code quickly.

On the first line, we have a using directive, used to import the System namespace. This allows us to refer to the Console type further on in the code without having to type its full name System.Console.

Next, we’re declaring a class named Program. The name doesn’t really matter, but it’s common practice to name the class containing the entry point of the application Program. Notice the use of curly braces to mark the start and end of the class declaration.

Inside the Program class, we declare a static method called Main. This special method is recognized by the common language runtime as the entry point of the managed code program and is where execution of the program will start. Notice the method declaration is indented relative to the containing class declaration. Although C# is not a whitespace-sensitive language, it’s good to be consistent about indentation.

Finally, inside the Main method we’ve written a couple of statements. The first one makes a method call to the Write method on the Console type, printing the string Enter your name: to the screen. In the second line, we read the user’s name from the console input and assign it to a local variable called name. This variable is used in the last statement, where we concatenate it to the string "Hello " using the + operator to print it to the console by using the WriteLine method on the Console type.

Compiling It

To run the code, we must compile it because C# is a compiled language (at least in today’s world without an interactive read-eval-print-loop [REPL] loop C# tool). The act of compiling the code results in an assembly ready to be executed on the .NET runtime.

Open a command prompt window and change the directory to the place where you saved the Hello.cs file. As an aside, the use of .cs as the extension is not a requirement for the C# compiler; it’s just a best practice to store C# code files as such.

Because the search path doesn’t contain the .NET Framework installation folder, we have to enter the fully qualified path to the C# compiler, csc.exe. Recall that it lives under the framework version folder in %windir%\Microsoft.NET\Framework. Just run the csc.exe command, passing in Hello.cs as the argument, as illustrated in Figure 3.9.

Figure 3.9

Figure 3.9. Running the C# compiler.

If the user has installed Visual Studio 2012, a more convenient way to invoke the compiler is from the Visual Studio 2012 command prompt. This specialized command prompt has search paths configured properly such that tools like csc.exe will be found.

Running It

The result of the compilation is an executable called hello.exe, meaning that we can run it immediately as a Windows application (see Figure 3.10). This differs from platforms like Java where a separate application is required to run the compiled code.

Figure 3.10

Figure 3.10. Our program in action.

That wasn’t too hard, was it? To satisfy our technical curiosity, let’s take a look at the produced assembly.

Inspecting Our Assembly with ILSpy

Knowing how things work will make you a better developer. One great thing about the use of an IL format in the .NET world is the capability to inspect compiled assemblies at any point in time without requiring the original source code.

Three commonly used tools to inspect assemblies include the .NET Framework IL disassembler tool (ildasm.exe), .NET Reflector from Red Gate, and ILSpy. For the time being, we’ll use ILSpy, which you can download for free from http://www.ilspy.net.

When you run the tool for the first time, it loads the ILSpy assembly as the assembly to inspect, including all of its dependencies, as shown in Figure 3.11.

Figure 3.11

Figure 3.11. ILSpy disassembling itself.

Because we’re not interested in the decompilation of ILSpy, we’ll load our own hello.exe using File, Open. This adds “hello” to the list of loaded assemblies, after which we can start to drill down into the assembly’s structure, as shown in Figure 3.12.

Figure 3.12

Figure 3.12. Inspecting the assembly structure in ILSpy.

Looking at this structure gives us a good opportunity to explain a few concepts briefly. As we drill down in the tree view, we start from the “hello” assembly we just compiled. Assemblies are just CLR concepts by themselves and don’t have direct affinity to file-based storage. Indeed, it’s possible to load assemblies from databases or in-memory data streams, too. Hence, the assembly’s name does not contain a file extension.

When expanding the assembly’s entry, we encounter a node with a {} logo. This indicates a namespace and is a result of ILSpy’s decompilation intelligence, as the CLR does not know about namespaces by itself. Namespaces are a way to organize the structure of APIs by grouping types in a hierarchical tree of namespaces (for example, System.Windows.Forms). To the CLR, types are always referred to—for example, in IL code—by their fully qualified name (like System.Windows.Forms.Label). In our little hello.exe program we didn’t bother to declare the Program class in a separate namespace, so ILSpy shows a “-” to indicate the global namespace.

Finally, we arrive at our Program type with the Main method inside it. Let’s take a look at the Main method now, simply by selecting it from the tree view. Figure 3.13 shows the result.

Figure 3.13

Figure 3.13. Disassembling the Main method.

The pane on the right shows the decompiled code back in C#. It’s important to realize this didn’t use the hello.cs source code file at all. The hello.exe assembly doesn’t have any link back to the source files from which it was compiled. “All” ILSpy does is reconstruct the C# code from the IL code inside the assembly. You can clearly see that’s the case because the name of the name variable was changed into str. ILSpy’s interpretation of our Main method is semantically correct, though; we could have written the code like this.

Notice the drop-down box in the toolbar at the top. Over there, we can switch to other views on the disassembled code (for example, plain IL). Let’s take a look at that, too, as shown in Figure 3.14.

Figure 3.14

Figure 3.14. IL disassembler for the Main method.

What you’re looking at now is the code as the runtime sees it to execute it. Notice a few things here:

  • Metadata is stored with the compiled method to indicate its characteristics: .method tells it’s a method, private controls visibility, cil reveals the use of IL code in the method code, and so on.
  • The execution model of the CLR is based on an evaluation stack, as revealed by the .maxstack directive and naming of certain IL instructions (pop and push, not shown in our little example).
  • Method calls obviously refer to the methods being called, but observe how there’s no trace left of the C# using-directive namespace import and how all names of methods are fully qualified (for example, [mscorlib]System.Console::WriteLine(string)).
  • Our local variable “name” has lost its name because the execution engine needs to know only about the existence (and type) of local variables, not their names. (The fact that it shows up as str is due to ILSpy’s attempt to be smart about making up variable names.)

You might have noticed a few strange things in the IL instructions for the Main method: Why are those nop (which stands for no operation) instructions required? The answer lies in the way we compiled our application, with optimizations turned off. This default mode causes the compiler to preserve the structure of the input code as much as possible to make debugging easier. In this particular case, the curly braces surrounding the Main method code body were emitted as nop instructions, which allows a breakpoint to be set on that line.

  • + Share This
  • 🔖 Save To Your Account