- Installing the .NET Framework
- Your First Application: Take One
- Visual Studio 2010
- Your First Application: Take Two
- Summary
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 2010. Later in this chapter, we'll get our feet back on the ground and explore the Visual Studio 2010 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 will be 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 it a generalized Hello program, asking the user for a name to send a greeting to.
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 REPL loop C# tool). The act of compiling the code will result in an assembly that's 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'll 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 Running the C# compiler.
If the user has installed Visual Studio 2010, a more convenient way to invoke the compiler is from the Visual Studio 2010 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 we can run it immediately as a Windows application (see Figure 3.10). This is different from platforms like Java where a separate application is required to run the compiled code.
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 .NET Reflector
Knowing how things work will make you a better developer for sure. One great thing about the use of an intermediate language format in the .NET world is the capability to inspect compiled assemblies at any point in time without requiring the original source code.
Two commonly used tools to inspect assemblies include the .NET Framework IL disassembler tool (ildasm.exe) and .NET Reflector from Red Gate. For the time being, we'll use .NET Reflector, which you can download from the Red Gate website at www.red-gate.com/products/reflector.
When you run the tool for the first time, a dialog like the one shown in Figure 3.11 will appear. Here you can populate the initial list of assemblies displayed by .NET Reflector. The choice doesn't really matter for our purposes, but I recommend selecting the v4.0 framework version because that's the one we'll be dealing with most often in this book.
Figure 3.11 Populating .NET Reflector's initial assembly list.
After you've done this, you'll see a short list of commonly used .NET assemblies being loaded from the GAC ready for inspection. At this point, we're not really interested in those assemblies but want to 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 Inspecting the assembly structure in .NET Reflector.
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.
In our case, the assembly has been stored on disk as a file, more specifically as a file called hello.exe. In .NET Reflector, we can observe this by the child node to our assembly, which is the hello.exe module. Assemblies can consist of one or more modules, but the most common case is to have just one module. We won't go into detail on this topic for now.
Next, we encounter a node with a {} logo. This indicates a namespace and is a result of .NET Reflector'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 .NET Reflector 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. Select the tree node for Main and press the spacebar key. Figure 3.13 shows the result.
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" .NET Reflector does is reconstruct the C# code from the IL code inside the assembly. You can clearly see that's the case because the Main method does only contain two statements according to .NET Reflector, even though we wrote it with three statements instead. .NET Reflector's view on our assembly 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 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.
- 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 .NET Reflector's attempt to be smart.)
The attentive reader will 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.