Skip to main content
Top

2010 | Book

Introducing Visual C# 2010

insite
SEARCH

About this book

If you’re new to C# programming, this book is the ideal way to get started. Respected author Adam Freeman guides you through the C# language by carefully building up your knowledge from fundamental concepts to advanced features.

The book gradually builds up your knowledge, using the concepts you have already grasped to support those that come next. You will explore all the core areas of the C# language and the .NET Framework on which it runs. Particular attention is paid to the creation of Web and Windows applications and data access—danger zones where novice programmers often go awry in their early coding attempts.

Introducing Visual C# 2010 is a comprehensive primer. Even if you have no previous programming experience, you can have confidence in the fact that you'll be able to build well constructed web and Windows applications of your own once you have finished reading this book.

Table of Contents

Frontmatter

Getting Started

Frontmatter
Chapter 1. Introduction

It should be clear that I am enthusiastic about C#. I think it is a super language that can be used to great effect. It is my hope that as you read through this book you will not only learn how to program in C# but also gain your own enthusiasm. There is a lot to like about C#, and our journey through the language and its features begins here.

Adam Freeman
Chapter 2. Getting Ready

In this chapter, you installed Visual Studio 2010 and SQL Server 2008 and upgraded the Silverlight development tools for Visual Studio. These are the key tools that you’ll use throughout the book. You also created a simple application using Visual Studio and then compiled and ran it, just to get used to the basic functions of the development environment.

Adam Freeman
Chapter 3. Understanding C# and the .NET Framework

In this chapter, I have put C# and the .NET Framework in context. You have seen the two major components of the .NET Framework and how these are related to C#. You have explored the topic of assemblies and looked at the key features of the .NET platform and how they have been used to create a wide suite of technology building blocks that give .NET its wide-ranging features and functionality. Your next step is to start learning the basics of C#. Chapter 4 starts with the fundamentals common to every language and sets the foundation for the chapters that follow.

Adam Freeman

The C# Language

Frontmatter
Chapter 4. C# Fundamentals and Keyword Reference

In this chapter, we looked at the fundamentals of the C# language, starting by taking a simple C# program and breaking it down to look at the different syntax elements. We looked at the type system and explored the differences between reference and value types—a distinction that causes many problems for programmers new to C#.

We looked at how you use C# to perform some of the most require programming tasks—assigning values to variables, selectively executing code statements, and iterating over data items. This chapter finished with a reference for the C# keywords and operators. These sections are very dry reading, but they can be useful when you know what you want to do but are not sure which keyword or operator will do it for you.

Adam Freeman
Chapter 5. Numeric and Boolean Types

In this chapter, we looked at the numeric and Boolean types that C# supports and the operations you can perform on them. These operations include basic arithmetic, working directly with the binary representation of numbers and, of course, expressing true and false values. You have seen how C# supports literals to make working with these types simpler. We used the numeric literal prefix and suffix features to control type inference and how we can convert between some types implicitly, while other conversions require the cast operator.

Adam Freeman
Chapter 6. Classes and Objects

In this chapter, we have examined two of the fundamental building blocks of C# programming: classes and objects. We have seen how classes act as blueprints for the creation of objects and how those objects can be modified to reflect changes in state and used to perform actions and calculations.

We also covered the three pillars of object orientation as they apply to classes and objects and learned how inheritance, encapsulation, and polymorphism can be used to create classes with less code that are easy to modify, extend, and maintain.

We saw how object reference can be converted from one type to another using implicit and explicit casting and how this differs from the boxing and unboxing approach used for value types. In looking at how C# supports casting, we saw how the is and as operators can be used to avoid problems when downcasting to a more specialized type.

Finally, we looked at the modifiers you can apply to classes to change their behavior, ranging from classes that cannot be derived to those that force derived classes to provide implementations of methods and other members before they can be used to instantiate objects. In the coming chapters, we’ll look at the different types of members that a class (and therefore an object) can contain.

Adam Freeman
Chapter 7. Fields

In this chapter, we have seen how to define, initialize, modify, and use fields, and we have seen how to expose those fields to other types using properties and directly. Fields, be they the regular kind or static or whether or not have constant values, are the backbone of classes, and we use them in C# to maintain the state of our program as it runs. In later chapters, we will see some specialized kinds of field, such as events and delegates, which we can use to build on the basic model to achieve very specific effects.

Adam Freeman
Chapter 8. Properties, Indexers, and Operators

In this chapter, we explored the flexible property, indexer, and custom operator features to look at the different ways they can be used. If you have come to C# from a language that doesn’t have an equivalent to these features, you might be asking, why not just use methods? You can certainly do that, but these are powerful and expressive convenience features that reduce code clutter and make working with C# objects more natural. You can certainly write C# programs without using properties, indexers, and operators, but I suggest you keep them in mind. They tend to grow on you as you begin to use them.

Adam Freeman
Chapter 9. Methods

In this chapter, we have taken a detailed look at defining, implementing, and using methods. Methods are the muscles of a C# program. The code statements contained in a method are executed to perform actions and calculations, and the definitions and modifiers define how those methods can be connected together. Without methods, there is no C# program.

We looked at the different types of parameter that can be used in methods, and we learned that parameters are how we pass data around a program. We explored overloading and overriding methods, which are two of the key concepts in object-oriented programming. Finally, we looked at some special kinds of methods: the Main method, the constructor, and so on. These special methods shape the way that programs are executed and objects are differentiated. Along the way, we saw several convenience features, ranging from optional parameters to compiler-generated iterator blocks. There was a lot of information to learn in this chapter, but a good understanding of methods is an essential foundation for effective C# programming.

Adam Freeman
Chapter 10. Delegates, Events, and Anonymous Methods

In this chapter, you have how delegates can be used to encapsulate references to static and instance methods and passed around like regular types. You have seen the limitations of delegates when they are shared between objects and how events address this shortcoming.

The convention for using events is widely adopted, and I recommend that you follow it in your own code. Not only does it make your code easier for other programmers to use, but it also helps you create events that can be overridden reliably in derived classes.

We looked briefly at the System.Func and System.Action types, both of which allow us to work with delegates without creating custom delegate types, and we looked at anonymous methods and lambda expressions, which allow us to implement delegates without having to define methods. We learned how anonymous methods and lambda expressions capture local variables and when those variables are evaluated. We’ll see a lot more of Func, Action, and lambda expressions when we explore some of the advanced C# language features such as LINQ and parallel programming.

Adam Freeman
Chapter 11. Namespaces

Namespaces are a flexible way of grouping types together to help organize your program. You don’t have to use namespaces in your code, but you do have to know how they work so that you can take full advantage of the .NET Framework class library, which contains thousands of useful types.

The flexibility of namespaces can lead to some problems, especially when it comes to ambiguity of type names. We saw how to use different techniques to work around name conflicts and name ambiguity, and although most programmers don’t encounter these problems regularly, it is good to know that they can be resolved when the need arises.

Adam Freeman
Chapter 12. Interfaces, Structs, and Enums

In this chapter, we have looked at three categories of C# type: the interface, the struct, and the enum. Most C# programmers spend most of their time working on classes, but these types have their place and can be very useful in certain circumstances: interfaces are useful when you want to impose consistency on classes and structs that are not otherwise related, structs are useful when you want to create custom value types, and enums are useful when you need to work with a fixed range of values.

Adam Freeman
Chapter 13. Arrays

In this chapter, we explored the different kinds of arrays that C# supports and the features that each kind has to offer. The most commonly used is the single-dimensional array that dominates this chapter. This kind of array allows you group together related objects in a simple and efficient way. We also looked at multidimensional arrays, which can be used to express more complex relationships between objects. They are less frequently used and can become complex and confusing to use as the number of dimensions increases. We saw how arrays of all types can be used, enumerated, and populated, as well as how to use the members inherited from the System.Array class to perform common array-related tasks.

Adam Freeman
Chapter 14. Exceptions

In this chapter, we have explored the mechanism that C# uses to express and process error conditions. We have thrown, caught, and handled the built-in exceptions that the .NET Framework includes for common problems and derived custom types that can be used for application-specific issues.

We have also covered the need to throw meaningful exceptions that are useful to other programmers and the importance of including as much relevant information as possible when throwing an exception. We have seen the convention of differentiating between different problems by throwing instances of different classes derived from System.Exception. Finally, we looked at aggregating exceptions when it is essential to indicate multiple, simultaneous issues—something that we will revisit when we come to look at parallel programming techniques later in this book.

Adam Freeman
Chapter 15. Generic and Anonymous Types

In this chapter, we examined generic and anonymous types. Generic types let us constrain the types that a class will work with but do so in a flexible way. Generics can take a while to get used to, but they can be invaluable, especially when it comes to collection classes, which are discussed in Part III of this book. We also looked at the advanced topic of generic covariance and contravariance. Don’t worry if these topics make no sense. This is a feature that causes even the best programmers to scratch their heads. If that section made little sense, then my advice is to ignore it for the moment, returning to only when the need arises. Most programs do not require covariant or contravariant generic classes to function.

At the end of this chapter, we took a brief look at anonymous types. Our examination was brief because they have such limited functionality. But don’t dismiss them. We will see them again in the LINQ chapter, where their power and flexibility will become apparent.

Adam Freeman
Chapter 16. Strings and Characters

Strings are important in any programming language, and C# is no exception. In this chapter, we looked at the C# support for individual characters and for strings, which represent sequences of characters. We saw how to use literal values to define character and string values and how to perform operations on both types. We explored the range of class members and operators available to make working with strings easier and looked at the System.Text.StringBuilder class, which is a mutable companion to the read-only System.String class.

We finished the chapter by looking at the composite formatting feature, which allows strings to be composed by embedding format items in strings, which become placeholders for string representations of other objects. We saw how to format the built-in numeric types and how to create custom format components.

Adam Freeman
Chapter 17. Attributes

In this chapter, we saw how the .NET attribute system allows you to apply modifiers to your custom types without having to add new keywords to C#. We started by looking at two of the built-in attributes, and I described how an attribute doesn’t have value until some other part of the system gives it meaning. In the examples we looked at, the meaning was provided by a method in a base class and the C# compiler.

We saw how to create and apply custom attributes and how to use reflection techniques to test to see whether attributes have been applied. This introduced topics that are covered fully in Chapter 23. The .NET Framework contains dozens of attributes, but they need to be described in context. We’ll see some of the most useful when we come to Chapter 23, and others are used in LINQ, the Entity Framework, and other applied .NET technologies.

Adam Freeman
Chapter 18. Garbage Collection

In this short chapter, we looked at how you can modify your classes to ensure that resources are released properly and that objects have a chance to tidy themselves up before they are destroyed by the garbage collector. We also looked at weak references, which allow you to create objects that are always candidates for destruction by the garbage collector.

Adam Freeman

The .NET Class Library

Frontmatter
Chapter 19. Collections

In this chapter, we took a tour of the generic collection classes, looking at lists, dictionaries, sets, queues, and stacks. These are classes that you will use day-in, day-out in your projects. You’ll probably use List<T> most often to begin with, because it can be used as a direct replacement for an array, which most programmers are already comfortable with. But the other collection classes are worth your attention also, so I suggest you take the time to understand them all.

We also looked at how to apply some collection-like features to arrays using the System.Array class. This is a very useful feature that doesn’t get as much attention as it deserves. Collections are a complement to arrays, not a replacement, and being able to treat an array as you would a collection can be a great time-saver.

Finally, we looked at how to create read-only collections and touched upon the legacy collections that have been part of the .NET class library since before C# supported generics. I strongly recommend that you stick to the generic classes, which have more features and where strong typing will help eliminate runtime exceptions.

Adam Freeman
Chapter 20. Files, Streams, and IO

In this chapter, we looked at how C# supports working with files and directories, using either the File and Directory or FileInfo and DirectoryInfo classes. We saw how to compose and manipulate file paths using the Path class and how to monitor a directory for changes and how to specify which changes we are interested in.

We also explored the support for streams, which are a general-purpose feature for reading and writing sequential byte data to a range of backing stores in a consistent way. Because working with byte values can be very tedious, we also looked at the reader and writer classes that make working with binary and textual representations of built-in type values a breeze.

Adam Freeman
Chapter 21. Networking & WCF

In this chapter you looked at the .NET Framework class library facilities for networking. You learned how to use the WebClient class to retrieve data from HTTP servers, how to use the TcpListener, TcpClient, and UdpClient classes to perform connection-oriented and connectionless networking, how to use the Dns class to retrieve DNS information, and how to use the HttpListener class to create a simple web server.

You also took a quick tour of the Windows Communications Foundation, which supports C# object and value semantics across networks—something that requires a little more work, but makes the resulting program more robust and natural to work with.

Adam Freeman
Chapter 22. Time & Dates

In this chapter you have seen how to use the .NET Framework class library to measure small amounts of time, represent periods of time, and represent moments in time. These are features that most programmers use frequently. One of the features I like most in the way that .NET and C# represent times and dates is the custom operators, which make comparing and combining dates and periods simple and elegant.

Adam Freeman
Chapter 23. Serialization

This chapter showed the four different approaches available for serializing objects. If you want to serialize data for use within or between .NET programs, the binary serializer offers the best performance and feature set. The Data Contract Serializer can be used to generate the most portable XML or JSON, both of which are suitable for creating data you can share with non-.NET programs and systems.

Adam Freeman
Chapter 24. Parallel Programming

This chapter explored one of my favorite C# topics—parallel programming using the Task Parallel Library (the other is LINQ, in case you were wondering). Parallel programming has remained a niche skill in recent years, despite the emergence of multi-core and multi-processor machines. Once reason for the niche status is the complexity in writing parallel programs, something which I think the TPL does a good job of addressing.

Effective parallel programing still requires an investment of time and patience because it requires a new approach to breaking down your problems and working out which data must be shared (and how it will be protected), but it is an investment that pays dividends—you can do more work with less equipment and at lower cost.

Adam Freeman
Chapter 25. Asynchronous Methods and Parallel Loops

In this chapter, you have learned about two simple alternatives to the Task-based parallel programming seen in Chapter 24. You first looked at asynchronous methods, which pre-date the Task Parallel Library. These methods can be used with library classes that implement Begin and End methods and, via delegates, with any method you are interested in. You also saw how to create a Task from an asynchronous method so that it can be used as the foundation for a continuation chain (see Chapter 24 for details of Task chains).

You also looked at parallel loops, which are built on the TPL and allow you to create parallel versions of the for and foreach loop. These loops can deliver significant performance increases over their sequentially-executed counterparts and are quick and simple to implement.

Adam Freeman
Chapter 26. Other Useful Features and Classes

In this chapter, we covered a wide range of topics that don’t really fit into the previous chapter. Sometimes, there is a poor fit because the technique or class mixes different techniques or because the feature is slightly too advanced for an introduction, but what all of these topics have in common is that they can be exceptionally useful under the right circumstances. Every programmer has their collection of favorite language tricks; in this chapter, I have shown you some of mine.

Adam Freeman

Data and Databases

Frontmatter
Chapter 27. LINQ to Objects

In this chapter, you were introduced to the world of LINQ and saw some demonstrations of using LINQ to Objects. LINQ can take a little while to get used to, but the flexibility and elegance that it can bring to a program is worth the investment in time. One of the best features of LINQ is consistency. As you will see the chapters that follow, everything that you have learned about to LINQ to Objects can be applied to LINQ to XML, LINQ to Entities, and so on. There are differences, but they are not as great as you might expect.

I have lost count of the number of times that I have been able to perform complex data transformations using LINQ to reduce complex legacy programs to a handful of simple queries. I encourage you to dig further into the details of LINQ and take the time to master of the best features available in C#.

Adam Freeman
Chapter 28. Parallel LINQ

In this chapter, you have taken a brief tour of the parallel version of LINQ to Objects—PLINQ. PLINQ lets you use the power of parallel processing on your LINQ queries with one method call. Depending on your query and data, the performance benefits can be enormous. You can use PLINQ without any reference to the Task class, which underpins the performance improvements. PLINQ is really a simple and powerful addition to LINQ.

Adam Freeman
Chapter 29. LINQ to XML

In this chapter, we saw how the classes in the System.Xml.Linq namespace can be used to create and represent XML data and how they have been designed to work well with LINQ queries. We saw how to work with XML data declaratively and how to do the same using LINQ queries. If you have used other XML processing APIs, such as SAX and DOM, then you will appreciate the flexibility and ease of use that LINQ to XML offers, and the ability to use LINQ queries and PLINQ queries is exceptionally useful.

Adam Freeman
Chapter 30. LINQ to Entities

In this chapter, we saw now the Entity Framework can be used to create a data model that lets us work with a database using C# data types and LINQ queries. Features such as navigation properties make working with the data much more like working with regular C# objects, and we don’t need to break out the SQL at any point. The Entity Framework can be used to create incredibly complex and sophisticated data models, and we have only scratched the surface with the model we used in this chapter, but even so, you can see how object-relational mapping can be performing using the Entity Framework and how LINQ to Entities can be used in place of SQL to query the underlying data.

Adam Freeman
Chapter 31. LINQ to DataSet

In this chapter, we looked at the DataSet class and its relationship with LINQ. If you want some of the convenience of a managed data environment but don’t want the overhead of the Entity Framework, then the DataSet functionality may be of use, especially given the support for in-memory queries that comes with LINQ to DataSet.

When using DataSet, you have to be much more aware of the structure and content of the database than when using an entity model, but in return you gain finer-grained control over the operations and queries that are performed. The approach that a project demands will depend on individual circumstances, but as you have seen from this and the preceding chapter, C# and .NET give you a lot of flexibility when it comes to working with databases.

Adam Freeman

User Interfaces

Frontmatter
Chapter 32. Windows Forms

In this chapter, we took a whistle-stop tour of Windows Forms, the oldest and most mature of the .NET user interface technologies. You have seen how the properties and events model are used to configure and wire up controls to create traditional Windows clients and how easy it is to integrate external data into such a program. We also looked at using the Windows API Code Pack, which provides support for accessing Windows 7/Vista-specific features such as jump lists and windows transparency.

Windows Forms has fallen out of favor since WPF arrived on the scene. This is a shame, because Windows Forms is rich in features and incredibly widely used. It lacks some of the flashy features that WPF supports, since these are rarely used in business programs. I recommend you don’t dismiss Windows Forms and consider it seriously for your interface projects.

Adam Freeman
Chapter 33. Windows Presentation Foundation

In this chapter, we used WPF to create the same stand-alone and data-centric programs we used Windows Forms for. There is a lot in common between these two technologies when building basic programs—a similar approach to properties and events, a drag-and-drop designer, and so on. But for every similarity, there is an important difference—XAML layout documents, control sets that don’t overlap exactly, and slightly different approaches to bind data to controls.

We also saw two features that are unique to WPF. The first was animations, which allows you to create rich interaction models by changing the characteristics of controls over periods of time. The second was the command feature, which lets you group controls by the functionality they add to your program and enable, disable, and work them as a single group.

WPF may lack some of the robustness and maturity of Windows Forms, but it has a much more modern foundation and some interaction features that can be used to add pleasing richness to interfaces. It is easy to understand why WPF is starting to gain ground.

Adam Freeman
Chapter 34. ASP.NET

In this chapter, we looked at two of the user interface components from the ASP.NET suite of technologies. The first, Web Forms, follows a similar model to the Windows Forms technology, allowing you build web applications by using controls, configuring them using properties, and responding to their operation using events. Web Forms is a very mature technology with a very wide adoption, especially in corporate intranet environments. We also looked at ASP.NET Dynamic Data, a relatively new addition to ASP.NET that makes it quick and simple to create fully featured data-centric applications. Web Forms can be used to create data applications, but the ASP.NET Dynamic Data feature is, to my mind, a simpler and more elegant approach for most ASP.NET projects.

Adam Freeman
Chapter 35. Silverlight

In this chapter, we took an introductory look at Silverlight, the .NET technology for creating highly interactive web applications. We saw how some of the core C# features and .NET Framework classes are available when writing Silverlight applications and how WPF provides the foundation for the user interface. We also looked at how WCF RIA services can simplify the use of remote services in Silverlight and how to generate service classes and methods that hide the WCF mechanics so that we can work with regular C# objects. Lastly, we look at the way that Silverlight clients can be installed and used outside the web browser, which is a nice way of getting the lightweight features of Silverlight but delivering a full Windows experience. Silverlight may not have the market penetration that Flash enjoys, but the tight integration with ASP.NET and other .NET features, such as WPF and WCF, goes some way to balancing this shortfall.

Adam Freeman

Advanced Topics

Frontmatter
Chapter 36. Windows Integration

In this chapter, we looked at the ways in which the .NET Framework Class Library provides support for accessing key features of the Windows operating system. Using C#, we have been able to use the event log, gain elevated privileges, create and install a Windows service, and make use of the registry. These features are not directly required by C# or .NET, but they can be very useful in making a C# program better fit into the Windows ecosystem.

Adam Freeman
Chapter 37. Cryptography and Security

In this chapter, we saw how to use the .NET cryptography features to perform common cryptographic operations, such as encryption, decryption, and hash code validation. The .NET Framework Class Library contains implementations of many encryption and has algorithms, some of which are implemented using underlying Windows features and others of which are written using .NET itself. We have also seen how to use the Data Protection API to encrypt data using keys that are maintained by Windows on behalf of users, which alleviates the user needing to remember additional information beyond their Windows credentials.

Adam Freeman
Chapter 38. Testing and Debugging

In this chapter, we looked at some of the C#, .NET, and Visual Studio features that you can use to improve the quality of your source code and reduce the likelihood of errors or unexpected behavior in your program. No single technique is perfect, but a combination of the approaches we have looked at can provide a great deal of insight into how your code will operate and the implicit assumptions that we all make when writing code. Few programmers like testing, but the more experienced you become with C# and .NET, the more you will appreciate how much of your time and your users’ time can be saved by improving the quality of your code.

Adam Freeman
Backmatter
Metadata
Title
Introducing Visual C# 2010
Author
Adam Freeman
Copyright Year
2010
Publisher
Apress
Electronic ISBN
978-1-4302-3172-1
Print ISBN
978-1-4302-3171-4
DOI
https://doi.org/10.1007/978-1-4302-3172-1

Premium Partner