About this book

C# is a wonderfully expressive and powerful language that lets you focus on your application rather than low level boilerplate. Over the last decade, the C# compiler has evolved to include many features from dynamic and functional languages, all while remaining statically typed. Most recently, it also tackles the proliferation of concurrent hardware with new asynchronous programming features.

"C# 5 First Look" will help you get up to speed on the latest version of the language. You will learn the underlying principles of the design by exploring its evolution, then look at the asynchronous and concurrent programming facilities of the Task Parallel Framework, and the new async and await keywords. The book also takes you through the development of real-world applications for Windows 8, ASP.NET, and MacOS, using the Mono Framework.

"C# 5 First Look" will help you get up to speed on the latest version of C#. After setting up your development environment, you will go on a tour of all features of the language, including: the Task Parallel Framework, Dynamic Language Runtime, TPL Data Flow, and finally asynchronous programming with async and await.

"C# 5 First Look" will help you get up to speed on the latest version of C#. We will discuss the tools you need to get started, including Visual Studio and MonoDevelop. Once set up, we look at the highlights of the language’s evolution over every version and discuss how the framework’s design and language features contribute to the high productivity you experience as a C# programmer. Next we check out the asynchronous and concurrent programming features of the language, which help you write fast and responsive applications. Finally, the book presents and explains three fully featured pieces of software that demonstrate writing applications for the Windows Store, the Web, and MacOS with the Mono Framework.

"C# 5 First Look" is a look at the evolution of C#. You will learn how to write great apps on all platforms using modern C# language features. Whether you are targeting the desktop, mobile, or web, C# 5 First Look has you covered.

Publication date:
December 2012
Publisher
Packt
Pages
138
ISBN
9781849686761

 

Chapter 1. Getting Started with C#

In this chapter, we will talk about the general state of the industry at the time when C# was first introduced, and some of the reasons that it is a great language. By the end of the chapter, you will have a fully working development environment that is ready to go through all of the examples in this book.

 

Origins


As every comic book super hero has an origin story, so does every professional in every walk of life. Sharing origin stories with your colleagues is great because it can serve as a point of reflection about how things were in the past, how they have evolved, and where they may go in the future. My own personal story originated in high school in the late nineties, watching my brother, who was five years my elder and in college, learning C++. With a few arcane instructions, complex programs came to life and were ready for action. I was fascinated.

This first glimpse of power was just the beginning. Around the same time, a friend of mine in class started working on a game, again written in C++, in the style of the NES game, The Legend of Zelda. Although I had briefly peeked at old QBasic games such as Gorillas in the past, I was amazed at the quality that he was able to achieve in his small demo. I decided to start learning how to program in earnest, and seeing as everyone I knew was using C++, that was the default choice for my first programming language.

The first program I ever wrote was a very simple financial budgeting program. Having just recently started working at my first job in high school, I was keenly aware of the new responsibilities involved in the management of money, and so I wanted to write a program to help me better manage my funds. First, it asked for the amount of my paycheck in dollars, and then for a list of bills that I had to pay.

After a few basic calculations, it gave me a report of how much disposable income would remain after my responsibilities were taken care of. As far as programs go, it was not the most complex piece of software, but it helped me learn the basics, such as loops, conditional statements, storage of an indeterminate list of items, and performing aggregate operations on an array.

It was a great personal triumph, but after some initial exploration with C++, I found myself hitting a bit of a brick wall. C++ was difficult to fully grasp as someone brand new to programming (and in high school). Not only did I have to learn about the basics of software, but I had to be constantly aware of the memory that I was using. Eventually, I discovered the tools of web development which were, to me at the time, much simpler to understand. I had moved from one end of the complexity spectrum to the other.

Much of the software landscape at that time was dominated by computer languages that sat in one of three camps: low level system languages such as C++, which offered the most in terms of performance and flexibility, but were also difficult and complex to master; interpreted languages such as JavaScript and VBScript, whose instructions were evaluated at runtime, were very easy to use and learn, but could not match the performance of low level languages; and finally a group of languages that come somewhere in the middle.

This middle of the road, which encompassed languages such as Java and Visual Basic, offered some of the best of both worlds, along with the worst of both worlds. In these languages you have a garbage collector , which means that when you create an object you do not have to explicitly release the used memory when you are done. They are also compiled to an intermediate language (for example, p-code for VB, and byte code for Java) which are then executed in a Virtual Machine running natively on the target platform. Because this intermediate language is similar to machine code, it is able to execute much faster than the purely interpreted languages. This performance, however, was still not really a match for a properly tuned C++ program, so Java and Visual Basic programs were often regarded as slow languages in comparison with C++.

Despite some of these drawbacks, the benefits of having a managed memory environment were evident to Microsoft. Because the programmer did not have to worry about complex concepts such as pointers and manual memory management, programs could be written faster and with fewer bugs. Rapid Application Development (RAD for short) seemed to be the future direction for Microsoft's platforms.

In the late nineties, they developed a version of the Java Virtual Machine, which by many accounts was faster than some of the other implementations available on the market. Unfortunately due to their inclusion of some proprietary extensions, and the fact that they did not completely implement the Java 1.1 standard, they ran into some legal troubles in 1997. This resulted ultimately in Microsoft discontinuing the development on their implementation of Java, and ultimately removing it from their platform in 2001.

Although it is impossible to know if what happened next was a direct result of the legal action against the Microsoft Java Virtual Machine, what we do know is that in 1999 Microsoft started working on a new programming language, which was named Cool (C-like Object Oriented Language).

C# is born

And then it happened; in 2000, Microsoft announced that they were working on a new programming language. The language which was originally called Cool, was unveiled at the Professional Developers Conference 2000 in Orlando, FL as C#. Some of the highlights of this new language are:

  • It is based on the syntax of the C family of programming languages, so the syntax was very familiar for anyone who had experience with C++, Java, or JavaScript.

  • Memory management of C# is similar to that of Java and Visual Basic, with a very powerful garbage collector. This meant that the users could focus on the content of their application, rather than worrying about boilerplate memory management code.

  • The C# compiler along with a static type system means that certain classes of bugs can be caught at compile time, rather than having to deal with them at runtime as you would in JavaScript. This is a Just-In-Time compiler , which means that the code would be compiled to a native executable at runtime, and optimized for the operating system that is executing the code. Performance is an important goal of the new platform.

  • This language has a strong and extensive base class library , which means that many pieces of functionality would be built right into the framework. Aside from some industry standard libraries such as Boost, there were not very many common C/C++ libraries, which resulted in people often rewriting common functionality. Java, on the other hand, had a great many libraries, but they were written by a diverse set of developers, which meant that consistency in functionality and style was a problem.

  • It also has interoperability with other languages that worked on the Common Language Runtime (CLR). So a single program could use functionality written in different languages, thus using each language for what it was best at.

  • Microsoft submitted the specification to the ISO working group. This opened the door to a vibrant open source community around the framework, because it meant that there would always be a standard to work against. A popular open source implementation of the .NET Framework and C# called Mono lets you run your code on different platforms.

Although none of the elements described in this list were particularly new, C# aimed to take the best aspects of programming languages that came before, and incorporate them, namely the strength and power of C++, the simplicity of JavaScript, and the ease of hosting of VBScript/ASP, among other things.

People coming from ANY language (C, C++, or Java) could be productive in C# with little effort. C# found the sweet spot where productivity, features, and the learning curve all intersected.

Over the next decade, the language would go on to evolve a very attractive set of features that make it easier and faster to write great programs. Now in its fifth iteration, the C# language has become more expressive and powerful with features, such as Language Integrated Queries (LINQ), Task Parallel Library (TPL), a Dynamic Language Runtime (DLR), and asynchronous programming features. What's more, with the Mono framework, you can not only target Windows, but also every other mainstream platform such as Linux, Mac OS, Android, iOS, and even game consoles such as the Playstation Vita.

Whether you have been writing C# for the last decade, or are just picking it up now, this book will take you through all of the features of the latest version 5.0. We will also explore the evolution and history of C# so that you can understand why certain features developed the way they did, and how you can use them to their full potential.

Before we begin though, we need to configure your computer to be able to compile all of the samples. This chapter will guide you through installing everything you need to go through every example in this book.

 

The tools


Whenever you approach a new programming language, or a tool, there are several questions that you can ask yourself in order to quickly become proficient in that environment, such as:

  • How do you build a program, or otherwise prepare it for deployment?

  • How do you debug a program? Quickly figuring out what the problem is, and where it is when there is one. This is just as important as writing the program in the first place.

In the following sections, we will review several tools that are available to you in order to get a development environment up and running on your local machine. These options vary across a number of different licensing terms and cost structures. No matter your situation or preferences, you will able to get a development environment up and running and you will be able to answer the previous questions by the end of the chapter.

Visual Studio

Microsoft provides the de facto compiler and development environment for the C# language. Although the compiler is available as a command-line executable since the first release of the .NET Framework, most developers will stay within the confines of Visual Studio, which is Microsoft's Integrated Development Environment (IDE).

Full versions of Visual Studio

Microsoft's full commercial offerings of Visual Studio come in several different versions, each with a cumulative number of features as you move up the ladder.

  • Professional: This is the base commercial package. It allows you to build all available projects, in all available languages. In the context of C#, some of the project types available are ASP.NET WebForms, ASP.NET MVC, Windows 8 App, Windows Phone, Silverlight, Library, Console, along with a robust testing framework.

  • Premium: In this version, all professional features are included, in addition to the code metrics, expanded testing tools, architecture diagramming, lab management, and project management features.

  • Ultimate: This version includes code clone analysis, more testing tools (including Microsoft Fakes), and IntelliTrace, in addition to all the features of the previous levels.

Check out these versions at http://www.microsoft.com/visualstudio/11/enus/products/visualstudio.

Licensing

There are several different options for licensing the full version of Visual Studio.

  • MSDN Subscription: The Microsoft Developer Network provides a subscription service where you can pay an annual fee to gain access to versions of Visual Studio. Additionally, you can get an MSDN Subscription as part of Microsoft's MVP program, which rewards the active community members in the development community. You can find more information about purchasing an MSDN Subscription at https://msdn.microsoft.com/en-us/subscriptions/buy/buy.aspx.

  • BizSpark: If you are creating a startup, Microsoft offers the BizSpark program to give you access to Microsoft software (including Visual Studio) at no cost for three years. After your graduation date, you keep the licenses that you've downloaded over the course of the program, and get discounts on MSDN Subscriptions, in addition to other alumni benefits. BizSpark is a great option for any entrepreneur that wants to use the Microsoft technology stack. Find out if you qualify for the BizSpark program at http://www.microsoft.com/bizspark.

  • DreamSpark: Students can enroll in the DreamSpark program, which lets you download Visual Studio Professional (in addition to other applications and servers). As long as you are a student in a valid academic institution, you will have access to everything you need to develop applications using C#.Students. Sign up today at https://www.dreamspark.com/.

  • Individual and Volume licensing: If none of the previous options for the commercial version of Visual Studio are appropriate, then you can always purchase licenses directly from Microsoft or various resellers at http://www.microsoft.com/visualstudio/en-us/buy/small-midsize-business.

Express

The Visual Studio Express product line is a nearly fully featured version of Visual Studio that is free of cost. Anyone can download these products and begin learning and developing at no charge.

The available versions are as follows:

  • Visual Studio Express 2012 for Windows 8: This is for creating Metro style applications for Windows 8

  • Visual Studio Express 2012 for Windows Phone: This lets you write programs for Microsoft's Windows Phone devices

  • Visual Studio Express 2012 for Web: All web applications can be built using this version of Visual Studio, from ASP.NET (forms and MVC), to Azure hosted projects

  • Visual Studio Express 2012 for Desktop: Applications that target the classic Windows 8 Desktop environment can be built with this version.

It's a common misconception that Visual Studio Express may only be used for non-commercial projects, but this is not the case. You are entirely free to develop and release a commercial product while still adhering to the EULA. The only limitations are technical, as follows:

  • Express versions of Visual Studio are limited by vertical stack, meaning you have to install a separate product for each project type that is supported (Web, desktop, phone, and so on). This is hardly a huge limitation though, and would only be a burden in the most complex of solutions.

  • There are no plugins. There are many productivity enhancing plugins that are available for the full version of Visual Studio, so for some users this exclusion can be a big deal. However, the good news is that one of the most popular plugins in recent memory, NuGet, is now being shipped with all versions of Visual Studio 2012. NuGet helps you manage your project's library dependencies. You can browse through the NuGet catalog and add open source third-party libraries, in addition to libraries from Microsoft.

The express versions of Visual Studio can be downloaded from http://www.microsoft.com/visualstudio/11/en-us/products/express.

Using Visual Studio

Regardless of which version of Visual Studio you decide to use, getting started is very simple once the product has been installed. The following are the steps:

  1. Launch Visual Studio, or if you are using Express, launch Visual Studio Express for Desktop.

  2. Create a new project by clicking on File | New Project….

  3. Choose Console Application from Installed | Templates | Visual C#.

  4. Give the project a name such as program, and click on OK.

  5. Add a line of code in the Main method as follows:

    Console.WriteLine("Hello World");
  6. Run the program by choosing Debug | Run without Debugger.

You will see the expected Hello World output and you are now ready to start using Visual Studio.

Command-line compiler

If you prefer to work at a lower level than with an IDE like Visual Studio, you can always opt to simply use the command-line compiler directly. Microsoft provides everything you need to compile C# code entirely for free by downloading and installing the .NET 4.5 Redistributable package from http://www.microsoft.com/en-us/download/details.aspx?id=8483.

Once that's downloaded and installed, you can find the compiler at C:\windows\microsoft.net\Framework\v4.0.30319\csc.exe, assuming you maintain all of the default installation options:

Note

Note that the .NET 4.5 version of the .NET Framework will actually replace the 4.0 framework if you have that installed. That's why the path mentioned previously shows as v4.0.30319. You won't be the first person confused by versions in the .NET Framework.

A small tip that will make working with the command-line compiler much easier is to simply add it to the environment's Path variable. If you're using PowerShell (which I highly encourage), you can easily do so by running the following command:

PS ~> $env:Path += ";C:\Windows\Microsoft.NET\Framework\v4.0.30319"

That makes it so you can just type csc instead of the whole path. Usage of the command-line compiler is very simple, take the following class:

using System;

namespace program
{
    class MainClass
    {
        static void Main (string[] args)
        {
            Console.WriteLine("Hello, World");
        }
    }
}

Save this class as a file named program.cs using your favorite text editor. Once saved, you can compile it from the command line using the following command:

PS ~\book\code\ch1> csc .\ch1_hello.cs

This will produce an executable file named ch1_hello.exe, which when executed, will produce a familiar greeting as follows:

PS ~\book\code\ch1> .\ch1_hello.exe
Hello, World

By default, csc will output an executable file. However, you can also produce libraries using the target argument. Consider the following class:

using System;

namespace program
{
    public class Greeter
    {
        public void Greet(string name)
        {
            Console.WriteLine("Hello, " + name);
        }
    }
}

This class encapsulates the functionality of the previous program, and even makes it reusable by letting you define the name to be greeted. Although this is a somewhat trite example, the point is to show how to create a .dll file that you can use from multiple programs.

PS ~\dev\book\code\ch1> csc /target:library .\ch1_greeter.cs

An assembly named ch1_greeter.dll will be generated, which you can then use from a slightly modified version of the previous program as follows:

using System;

namespace program
{
    class MainClass
    {
        static void Main (string[] args)
        {
            Greeter greeter = new Greeter();
            greeter.Greet("Componentized World");
        }
    }
}

If you try to compile the previous program just as you did before, the compiler will rightly complain about not knowing anything about the Greeter class as follows:

PS ~\book\code\ch1> csc .\ch1_greeter_program.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17626
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

ch1_greeter_program.cs(9,13): error CS0246: The type or
        namespace name 'Greeter' could not be found (are you
        missing a using directive or an assembly reference?)
ch1_greeter_program.cs(9,35): error CS0246: The type or
        namespace name 'Greeter' could not be found (are you
        missing a using directive or an assembly reference?)

Any time you have an error in your programs, it will be shown in the output, along with information about the file it was found in, and the line, so you can find it easily. In order for this to work, you will have to tell the compiler to use the ch1_greeter.dll file that you created using the /r: argument as follows:

PS ~\book\code\ch1> csc /r:ch1_greeter.dll .\ch1_greeter_program.cs

And now when you run the resulting ch1_greeter_program.exe program, you will see the output say, Hello, Componentized World.

Though most developers will not use the command-line compiler directly these days, it is good to know that it is available and also how to use it, especially if you have to support advanced scenarios such as merging multiple modules into a single assembly.

SharpDevelop

When you launch SharpDevelop, the tagline on the loading screen, The Open Source .NET IDE, is a concise description. since the very early days of the .NET Framework, it provided developers a free option for writing C# before Microsoft shipped the Express versions. Since that time, it has continued to mature, and add features, and as of version 4.2, SharpDevelop supports targeting the .NET 4.5, and more specifically, compilation and debugging of C# 5.0. Although Visual Studio Express is a compelling option, the lack of source control plugins can be a deal breaker for some users. Thankfully, SharpDevelop will gladly let you integrate with a source control server in the IDE. Additionally, some of the more niche project types such as creating Windows Services (one of the few project types not supported by Express) are fully supported with SharpDevelop.

Projects use the same format (.sln, .csproj) as Visual Studio, so project portability is high. You can usually take a project written in Visual Studio and open it in SharpDevelop.

Download the application from http://www.icsharpcode.net/OpenSource/SD/.

Installation is straightforward, and you can verify correct installation by creating the following sample program:

  1. Start SharpDevelop.

  2. Create a new project by clicking on File | New | Solution.

  3. Choose Console Application from C# | Windows Application.

  4. Give the project a name such as program, and click on Create.

  5. Right-click on the project node in the Projects window, and choose the Properties menu item; check the Compiling tab to see if the Target Framework says .NET Framework 4.0 Client Profile.

  6. If it does, then simply click on the Change button, select .NET Framework 4.5 in the Change Target Framework drop-down menu, and finally click on the Convert button.

  7. Run the program by choosing Debug | Run without Debugger.

You will see the expected Hello World output.

MonoDevelop

The Mono framework is an open source version of the Common Language Runtime and C#. It has had over a decade of active development, and as a result, is very mature and stable. There are versions of Mono for just about any platform you might be interested in developing for Windows, OS X, Unix/Linux, Android, iOS, PlayStation Vita, Wii, and Xbox 360.

MonoDevelop is based on SharpDevelop, but was forked some time ago to specifically act as a development environment for Mono that would run on multiple platforms. It runs on Windows, OS X, Ubuntu, Debian, SLE, and openSUSE; so, as a developer, you can truly choose what platform you want to work on.

You can get started by installing the Mono Development Kit 2.11 or higher from http://www.go-mono.com/mono-downloads/download.html.

Once you have installed that for your platform, you can go ahead and install the latest version of MonoDevelop from http://monodevelop.com/.

Using the C# 5.0 compiler is but a few short steps away:

  1. Start MonoDevelop.

  2. Create a new project by clicking on File | New | Solution….

  3. Choose Console Application from the C# menu.

  4. Give the project a name such as program, and click on Forward, then on OK.

  5. Right-click on the project node in the Solution window, and choose the Options menu item. Now go to Build | General to see if the Target Framework says Mono / .NET 4.0.

  6. If it does, then simply choose .NET Framework 4.5 from the dropdown and click on the OK button.

  7. Run the program by choosing Run | Start without Debugging.

If all goes well, you will see a terminal window (if running on OS X, for example) with the Hello World text.

 

Summary


When it was introduced, C# came as a breath of fresh air at just the right time. It is a modern object oriented language, which takes the best qualities of many that came before it. Low-level power with just-in-time compilation, the simplicity of a garbage collected environment, and the flexibility of runtime that allows for easy interoperability with other languages, not to mention a great base class library, thriving open source community, and the ability to target multiple platforms make C# a compelling option.

In this chapter, we discussed setting up your development environment and downloading all of the relevant tools and runtimes:

  • Visual Studio, both commercial and free options.

  • Command line, useful for plugging directly into automated tools that use shell commands.

  • SharpDevelop, an open source alternative to Visual Studio.

  • MonoDevelop, the official IDE of the open source implementation of the .NET Framework and C#. This allows you to target multiple platforms.

Once you have chosen a preferred development environment, and followed the steps detailed in this chapter, you will be ready to go through the rest of the book and all of the samples contained therein.

In the next chapter, we will talk about the evolution of the language, which, in turn, will help you understand the feature that was introduced along the way and contributes to where we stand today with C# 5.0.

About the Author

  • Joel Martinez

    Joel Martinez has most recently been focusing on mobile app development (Android, iOS, Windows Phone/RT). In the past, he founded the Orlando .NET User Group (ONETUG), worked at a few startups, made a few games, and was a Microsoft XNA MVP for a few years. You can find him on Twitter (@joelmartinez), or on the web at http://codecube.net.

    He also co-authored:

    • ASP.NET Development with Macromedia Dreamweaver MX (Peachpit Press, 2002)
    • Dreamweaver MX 2004 Magic (New Riders, 2003)

    Browse publications by this author
C# 5 First Look
Unlock this book and the full library FREE for 7 days
Start now