Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

INTRODUCTION

INTRODUCTION

IF WE WERE TO DESCRIBE THE C# LANGUAGE AND ITS ASSOCIATED ENVIRONMENT, the .NET Framework, as the most significant technology for developers around right now, we would not be exaggerating. .NET is designed to provide an environment within which you can develop almost any application to run on Windows, while C# is a programming language that has been designed specifically to work with the .NET Framework. By using C#, you can, for example, write a dynamic web page, a Windows Presentation Foundation application, an XML Web service, a component of a distributed application, a database access component, a classic Windows desktop application, or even a new smart client application that allows for online/offline capabilities. This book covers the .NET Framework 4. If you are coding using any of the prior versions, there may be sections of the book that will not work for you. We try to notify you of items that are new and specific to the .NET Framework 4.

Don't be fooled by the .NET label in the Framework's name and think that this is a purely Internet-focused framework. The NET bit in the name is there to emphasize Microsoft's belief that distributed applications, in which the processing is distributed between client and server, are the way forward. It is also important to understand that C# is not just a language for writing Internet or network-aware applications. It provides a means for you to code up almost any type of software or component that you need to write for the Windows platform. Between them, C# and .NET have revolutionized the way that developers write their programs and have made programming on Windows much easier than it has ever been before.

So what's the big deal about .NET and C#?

THE SIGNIFICANCE OF .NET AND C#

To understand the significance of .NET, it is useful to remind ourselves of the nature of many of the Windows technologies that have appeared in the past 18 years or so. Although they may look quite different on the surface, all of the Windows operating systems from Windows 3.1 (introduced in 1992) through Windows 7 and Windows Server 2008 R2 have the same familiar Windows API at their core. As we have progressed through new versions of Windows, huge numbers of new functions have been added to the API, but this has been a process of evolving and extending the API rather than replacing it.

The same can be said for many of the technologies and frameworks that we have used to develop software for Windows. For example, COM (Component Object Model) originated as OLE (Object Linking and Embedding). Originally, it was largely a means by which different types of Office documents could be linked, so that you could place a small Excel spreadsheet in your Word document, for example. From that it evolved into COM, DCOM (Distributed COM), and eventually COM+ — a sophisticated technology that formed the basis of the way almost all components communicated, as well as implementing transactions, messaging services, and object pooling.

Microsoft chose this evolutionary approach to software for the obvious reason that it is concerned about backward compatibility. Over the years, a huge base of third-party software has been written for Windows, and Windows would not have enjoyed the success it has had if every time Microsoft introduced a new technology it broke the existing code base!

Although backward compatibility has been a crucial feature of Windows technologies and one of the strengths of the Windows platform, it does have a big disadvantage. Every time some technology evolves and adds new features, it ends up a bit more complicated than it was before.

It was clear that something had to change. Microsoft could not go on forever extending the same development tools and languages, always making them more and more complex in order to satisfy the conflicting demands of keeping up with the newest hardware and maintaining backward compatibility with what was around when Windows first became popular in the early 1990s. There comes a point where you have to start with a clean slate if you want a simple yet sophisticated set of languages, environments, and developer tools, which makes it easy for developers to write state-of-the-art software.

This fresh start is what C# and .NET were all about in the first incarnation. Roughly speaking, .NET is a framework — an API — for programming on the Windows platform. Along with the .NET Framework, C# is a language that has been designed from scratch to work with .NET, as well as to take advantage of all the progress in developer environments and in our understanding of object-oriented programming principles that have taken place over the past 25 years.

Before we continue, we should make it clear that backward compatibility has not been lost in the process. Existing programs will continue to work, and .NET was designed with the capability to work with existing software. Presently, communication between software components on Windows takes place almost entirely using COM. Taking this into account, the .NET Framework does have the capability to provide wrappers around existing COM components so that .NET components can talk to them.

It is true that you don't need to learn C# in order to write code for .NET. Microsoft has extended C++, and made substantial changes to Visual Basic to turn it into a more powerful language, in order to allow code written in either of these languages to target the .NET environment. These other languages, however, are hampered by the legacy of having evolved over the years rather than having been written from the start with today's technology in mind.

This book will equip you to program in C#, while at the same time provide the necessary background in how the .NET architecture works. We not only cover the fundamentals of the C# language but also go on to give examples of applications that use a variety of related technologies, including database access, dynamic web pages, advanced graphics, and directory access.

ADVANTAGES OF .NET

So far, we've talked in general terms about how great .NET is, but we haven't said much about how it helps to make your life as a developer easier. This section briefly identifies some of the improved features of .NET.

  • Object-oriented programming — Both the .NET Framework and C# are entirely based on object-oriented principles right from the start.

  • Good design — A base class library, which is designed from the ground up in a highly intuitive way.

  • Language independence — With .NET, all of the languages — Visual Basic, C#, and managed C++ — compile to a common Intermediate Language. This means that languages are interoperable in a way that has not been seen before.

  • Better support for dynamic web pages — Though Classic ASP offered a lot of flexibility, it was also inefficient because of its use of interpreted scripting languages, and the lack of object-oriented design often resulted in messy ASP code..NET offers an integrated support for web pages, using ASP.NET. With ASP.NET, code in your pages is compiled and may be written in a .NET-aware high-level language such as C# or Visual Basic 2010. .NET now takes it even further with outstanding support for the latest web technologies such as Ajax and jQuery.

  • Efficient data access — A set of .NET components, collectively known as ADO.NET, provides efficient access to relational databases and a variety of data sources. Components are also available to allow access to the file system, and to directories. In particular, XML support is built into .NET, allowing you to manipulate data, which may be imported from or exported to non-Windows platforms.

  • Code sharing — .NET has completely revamped the way that code is shared between applications, introducing the concept of the assembly, which replaces the traditional DLL. Assemblies have formal facilities for versioning, and different versions of assemblies can exist side by side.

  • Improved security — Each assembly can also contain built-in security information that can indicate precisely who or what category of user or process is allowed to call which methods on which classes. This gives you a very fine degree of control over how the assemblies that you deploy can be used.

  • Zero-impact installation — There are two types of assemblies: shared and private. Shared assemblies are common libraries available to all software, whereas private assemblies are intended only for use with particular software. A private assembly is entirely self-contained, so the process of installing it is simple. There are no registry entries; the appropriate files are simply placed in the appropriate folder in the file system.

  • Support for Web services — .NET has fully integrated support for developing Web services as easily as you would develop any other type of application.

  • Visual Studio 2010 — .NET comes with a developer environment, Visual Studio 2010, which can cope equally well with C++, C#, and Visual Basic 2010, as well as with ASP.NET or XML code. Visual Studio 2010 integrates all the best features of the respective language-specific environments of all the previous versions of this amazing IDE.

  • C# — C# is a powerful and popular object-oriented language intended for use with .NET.

We look more closely at the benefits of the .NET architecture in Chapter 1, ".NET Architecture."

WHAT'S NEW IN THE .NET FRAMEWORK 4

The first version of the .NET Framework (1.0) was released in 2002 to much enthusiasm. The .NET Framework 2.0 was introduced in 2005 and was considered a major release of the Framework.

The .NET Framework 4 is another major release of the product with many outstanding new features.

With each release of the Framework, Microsoft has always tried to ensure that there were minimal breaking changes to code developed. Thus far, Microsoft has been very successful at this goal.

The following section details some of the changes that are new to C# 2010 and the .NET Framework 4.

Dynamic Typing

The world of programming has seen tremendous growth in dynamic languages such as JavaScript, Python, and Ruby. Because of the growing popularity of this type of programming, Microsoft has released a new dynamic typing capability in C#. It is not always possible to know statically what objects might end up being. Instead of using the object keyword and making everything of this type, we can now let the Dynamic Language Runtime (DLR) figure this out at runtime.

Using the new dynamic capabilities of C#, you now have a better interoperability story. You are able to interop with various dynamic languages and work with the DOM more easily. It's even simple to work with the Microsoft Office COM APIs now.

In this release of the .NET Framework 4, Microsoft has included the Dynamic Language Runtime. The DLR has been built upon the Common Language Runtime (CLR) to provide the ability to tie together all the dynamic language interactions.

C# provides access to the new DLR through the use of the new dynamic keyword. This is a flag to the compiler; whenever this keyword is encountered, the compiler will realize that it is a dynamic invocation and not the typical static invocation.

Optional and Named Parameters

Optional parameters and named parameters have been in Visual Basic for some time but have not been available to C# until the .NET 4 release. Optional parameters allow you to provide default values for some of the parameters of your methods and allow for a type of overloading by the consumer, even if there is only a single method in place to deal with all the variants. Here's an example:

public void CreateUser(string firstname, string lastname,
bool isAdmin, bool isTrialUser)
{

}

If you wanted to overload this and have default values for the two bool objects, then you could easily have a few more methods that populate these values for the consumer and then make a call to the master method to actually create the user. Now with optional parameters, you are able to do something like this:

public void CreateUser(string firstname, string lastname,
 bool isAdmin = false, bool isTrialUser = true)
{

}

Looking over this bit of code, the parameters firstname and lastname do not have a default value set, while isAdmin and isTrailUser do have default values set. As a consumer of something like this, you are now able to do some of the following:

myClass.CreateUser("Bill", "Evjen");
myClass.CreateUser("Bill", "Evjen", true);
myClass.CreateUser("Bill", "Evjen", true, false);
myClass.CreateUser("Bill", "Evjen", isTrailUser: false);

The last example makes use of named parameters, which are also a new feature for C# in this release of the .NET Framework. Named parameters will potentially change the way you write your code. This new feature will allow you to make your code easier to read and understand. As an example of this in action, take a look at the File.Copy() method of the System.IO namespace. Typically, it would be constructed similarly to this:

File.Copy(@"C:\myTestFile.txt", @"C:\myOtherFile.txt", true);

In this case, this simple method is working with three parameters, but what are the actual items being passed into the Copy() method? Unless you know this method backward and forward, it is hard to tell what is going on by just glancing at this method. Using named parameters, you are able to use the parameter name in the code prior to the value being provided, as in the following example:

File.Copy(sourceFileName: @"C:\myTestFile.txt",
   destFileName: @"C:\myOtherFile.txt", overwrite: true);

Now with the named parameters in place, you can more easily read and understand what is going on with this line of code. Using named parameters makes no difference to the resulting compilation; they are only used in the coding of the application.

Covariance and Contravariance

Covariance and contravariance were included in prior versions of the .NET Framework, but they have been extended in .NET 4 to perform even better when working with generics, delegates, and more. In the prior versions of .NET, you were able to use contravariance with objects and arrays, but, for instance, you were unable to use contravariance with generic interfaces. In .NET 4, you are able to do this.

ASP.NET MVC

ASP.NET MVC is the latest major addition to ASP.NET and has generated a lot of excitement in the development community. ASP.NET MVC supplies you with the means to create ASP.NET using the model-view-controller model that many developers expect. ASP.NET MVC provides developers with testability, flexibility, and maintainability in the applications they build. It is important to remember that ASP.NET MVC is not meant to be a replacement for the ASP.NET everyone knows and loves, but is simply a different way to construct your applications.

This release of ASP.NET allows you to build using this new model. You will find that it is completely built in to the Framework and Visual Studio.

WHERE C# FITS IN

In one sense, C# can be seen as being the same thing to programming languages that .NET is to the Windows environment. Just as Microsoft has been adding more and more features to Windows and the Windows API over the past decade and a half, Visual Basic 2010 and C++ have undergone expansion. Although Visual Basic and C++ have ended up as hugely powerful languages as a result of this, both languages also suffer from problems because of the legacies left over from the way they evolved.

In the case of Visual Basic 6 and earlier versions, the main strength of the language was the fact that it was simple to understand and made many programming tasks easy, largely hiding the details of the Windows API and the COM component infrastructure from the developer. The downside to this was that Visual Basic was never truly object oriented, so that large applications quickly became disorganized and hard to maintain. As well, because Visual Basic's syntax was inherited from early versions of BASIC (which, in turn, was designed to be intuitively simple for beginning programmers to understand, rather than to write large commercial applications), it didn't really lend itself to well-structured or object-oriented programs.

C++, on the other hand, has its roots in the ANSI C++ language definition. It is not completely ANSI-compliant for the simple reason that Microsoft first wrote its C++ compiler before the ANSI definition had become official, but it comes close. Unfortunately, this has led to two problems. First, ANSI C++ has its roots in a decade-old state of technology, and this shows up in a lack of support for modern concepts (such as Unicode strings and generating XML documentation) and for some archaic syntax structures designed for the compilers of yesteryear (such as the separation of declaration from definition of member functions). Second, Microsoft has been simultaneously trying to evolve C++ into a language that is designed for high-performance tasks on Windows, and in order to achieve that, it has been forced to add a huge number of Microsoft-specific keywords as well as various libraries to the language. The result is that on Windows, the language has become a complete mess. Just ask C++ developers how many definitions for a string they can think of: char*, LPTSTR, string, CString (MFC version), CString (WTL version), wchar_t*, OLECHAR*, and so on.

Now enter .NET — a completely revolutionary environment that has brought forth new extensions to both languages. Microsoft has gotten around this by adding yet more Microsoft-specific keywords to C++, and by completely revamping Visual Basic to the current Visual Basic 2010, a language that retains some of the basic VB syntax, but that is so different in design from the original VB that it can be considered, for all practical purposes, a new language.

It is in this context that Microsoft has provided developers an alternative — a language designed specifically for .NET, and designed with a clean slate. C# is the result. Officially, Microsoft describes C# as a "simple, modern, object-oriented, and type-safe programming language derived from C and C++." Most independent observers would probably change that to "derived from C, C++, and Java." Such descriptions are technically accurate but do little to convey the beauty or elegance of the language. Syntactically, C# is very similar to both C++ and Java, to such an extent that many keywords are the same, and C# also shares the same block structure with braces ({}) to mark blocks of code and semicolons to separate statements. The first impression of a piece of C# code is that it looks quite like C++ or Java code. Beyond that initial similarity, however, C# is a lot easier to learn than C++, and of comparable difficulty to Java. Its design is more in tune with modern developer tools than both of those other languages, and it has been designed to provide, simultaneously, the ease of use of Visual Basic and the high-performance, low-level memory access of C++, if required. Some of the features of C# are:

  • Full support for classes and object-oriented programming, including both interface and implementation inheritance, virtual functions, and operator overloading.

  • A consistent and well-defined set of basic types.

  • Built-in support for automatic generation of XML documentation.

  • Automatic cleanup of dynamically allocated memory.

  • The facility to mark classes or methods with user-defined attributes. This can be useful for documentation and can have some effects on compilation (for example, marking methods to be compiled only in debug builds).

  • Full access to the .NET base class library, as well as easy access to the Windows API (if you really need it, which will not be very often).

  • Pointers and direct memory access are available if required, but the language has been designed in such a way that you can work without them in almost all cases.

  • Support for properties and events in the style of Visual Basic.

  • Just by changing the compiler options, you can compile either to an executable or to a library of .NET components that can be called up by other code in the same way as ActiveX controls (COM components).

  • C# can be used to write ASP.NET dynamic web pages and XML Web services.

Most of these statements, it should be pointed out, do also apply to Visual Basic 2010 and Managed C++. The fact that C# is designed from the start to work with .NET, however, means that its support for the features of .NET is both more complete and offered within the context of a more suitable syntax than those of other languages. Although the C# language itself is very similar to Java, there are some improvements; in particular, Java is not designed to work with the .NET environment.

Before leaving the subject, it is important to point out a couple of limitations of C#. The one area the language is not designed for is time-critical or extremely high-performance code — the kind where you really are worried about whether a loop takes 1,000 or 1,050 machine cycles to run through, and you need to clean up your resources the millisecond they are no longer needed. C++ is likely to continue to reign supreme among low-level languages in this area. C# lacks certain key facilities needed for extremely high-performance apps, including the ability to specify inline functions and destructors that are guaranteed to run at particular points in the code. However, the proportions of applications that fall into this category are very low.

WHAT YOU NEED TO WRITE AND RUN C# CODE

The .NET Framework 4 will run on Windows XP, 2003, 7, and the latest Windows Server 2008 R2. In order to write code using .NET, you will need to install the .NET 4 SDK.

In addition, unless you are intending to write your C# code using a text editor or some other third-party developer environment, you will almost certainly also want Visual Studio 2010. The full SDK is not needed to run managed code, but the .NET runtime is needed. You may find you need to distribute the .NET runtime with your code for the benefit of those clients who do not have it already installed.

WHAT THIS BOOK COVERS

This book starts by reviewing the overall architecture of .NET in Chapter 1 in order to give you the background you need to be able to write managed code. After that, the book is divided into a number of sections that cover both the C# language and its application in a variety of areas.

Part I: The C# Language

This section gives a good grounding in the C# language itself. This section doesn't presume knowledge of any particular language, although it does assume you are an experienced programmer. You start by looking at C#'s basic syntax and data types, and then explore the object-oriented features of C# before moving on to look at more advanced C# programming topics.

Part II: Visual Studio

This section looks at the main IDE utilized by C# developers worldwide: Visual Studio 2010. The two chapters in this section look at the best way to use the tool to build applications based on the .NET Framework 4. In addition, this section also focuses on the deployment of your projects.

Part III: Foundation

In this section, you look at the principles of programming in the .NET environment. In particular, you look at security, threading, localization, transactions, how to build Windows services, and how to generate your own libraries as assemblies, among other topics.

Part IV: Data

Here, you look at accessing databases with ADO.NET and LINQ, and at interacting with directories and files. This part also extensively covers support in .NET for XML and on the Windows operating system side, and the .NET features of SQL Server 2008.

Part V: Presentation

This section starts with coverage on building classic Windows applications, which are called Windows Forms in .NET. Windows Forms are the thick-client version of applications, and using .NET to build these types of applications is a quick and easy way of accomplishing this task. This section also shows how to build applications based upon the Windows Presentation Foundation and Silverlight, and covers writing components that will run on web sites, serving up web pages. Finally, it includes coverage of the tremendous number of features that ASP.NET and ASP.NET MVC provide.

Part VI: Communication

This section is all about communication. It covers services for platform-independent communication using the Windows Communication Foundation (WCF). With Message Queuing, asynchronous disconnected communication is shown. This section looks at utilizing the Windows Workflow Foundation (WF), as well as peer-to-peer networking, and creating syndication feeds.

Appendix

The book closes with an appendix covering Windows 7 and Windows Server 2008 R2 development.

Online Chapters

Even with such a large book, we can't fit in everything we'd like to tell you about C# and using this language with other .NET technologies, so we've made ten additional chapters available online at www.wrox.com. These chapters include information on a variety of topics: GDI+, which is a technology that is used for building applications that include advanced graphics; .NET Remoting for communication between .NET clients and servers; Enterprise Services for the services in the background; and the Managed Add-In Framework (MAF). Some other big topics found online include VSTO development and working with LINQ to SQL.

CONVENTIONS

To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.

NOTE

Boxes with a warning icon like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

NOTE

The pencil icon indicates notes, tips, hints, tricks, or asides to the current discussion.

As for styles in the text:

  • We highlight new terms and important words when we introduce them.

  • We show keyboard strokes like this: Ctrl+A.

  • We show file names, URLs, and code within the text like so: persistence.properties.

  • We present code in two different ways:

    We use a monofont type with no highlighting for most code examples.
    We use bold to emphasize code that's particularly important in the present context or to show
    changes from a previous code snippet.
    
    					  

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at http://www.wrox.com. Once at the site, simply locate the book's title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.

NOTE

Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978-0-470-50225-9.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list including links to each book's errata is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don't spot "your" error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We'll check the information and, if appropriate, post a message to the book's errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

  1. Go to p2p.wrox.com and click the Register link.

  2. Read the terms of use and click Agree.

  3. Complete the required information to join as well as any optional information you wish to provide and click Submit.

  4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

NOTE

You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.