Home > Articles > Programming > C#

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020