Chapter 1. Introduction to C# 2.0

IN THIS CHAPTER

This chapter provides a brief introduction to the world of C#. As you will see, the syntax of the language itself is fairly easy to learn. The thing that takes the most time is learning how to program on the .NET Framework using the C# language. You will see the basic syntax of the C# language, including how to declare variables, create code blocks, and of course, create your first “Hello World” application.

If you already have a working knowledge of the C# language from your experience with previous versions (either 1.0 or 1.1), you can skip this chapter and move on. Take care not to skip too many of the early chapters, as there have been enhancements to the language that are covered early on in the book, such as generics and anonymous methods. This chapter also skips over some details that you may not be aware of if you have very little exposure to programming. If you have never written software on the Windows platform (either Windows or Web-based), this is the wrong chapter, and perhaps the wrong book, for you.

What Is the .NET Framework?

Before you learn the mechanics of the C# language itself, it is important that you learn the evolution of technologies that created the need for a language like C#. This section takes you on a quick tour of the history of C#, followed by an explanation of the Common Language Runtime, the Common Type System, and concluding with an overview of garbage-collected environments.

The Evolution of .NET

Before the .NET Framework was released to the public, the majority of component-oriented development for the Windows platform took the form of COM objects. Component Object Model (COM), a binary standard for creating reusable components, allowed developers to write code that solved smaller problems in smaller problem domains. By breaking down the problem into components, the solution often became easier and the components used to solve the problem could be reused to solve other similar problems.

COM offered many advantages and disadvantages. One of the most common problems with the COM standard was appropriately dubbed “DLL hell.” DLL hell arose when COM interfaces were indexed in the registry and then newer versions of those components were released. Versioning often caused developers headaches due to the tightly coupled, binary nature of the standard. In addition, if a DLL’s location changed on the file system without the information in the registry being modified, the COM interfaces contained within that DLL would become inaccessible. You could see examples of this when a new application was installed with a different version of some shared component, and it would not only break the new application, but all other applications using that component as well.

Other problems with development at the time included things like difficulty managing memory, slow development times, GUI controls that were typically insufficient for many tasks, as well as a lack of interoperability between languages such as C++ and Visual Basic.

As a solution to this and countless other problems with development at the time, Microsoft began working on what was then referred to as COM+ 2.0. The solution would provide a managed environment in which code would be executed that would provide for enhanced type safety, security, and an incredibly extensive library of useful classes and functions to make the lives of developers much easier. Eventually this solution became what is now the .NET Framework. Versions 1.0 and 1.1 have been released and now version 2.0 is available. In the next few sections, some of the key aspects of the .NET Framework will be discussed: the Common Language Runtime, the Common Type System, and the concept of garbage-collected managed code.

The Common Language Runtime

Before talking about the basics of C#, you need to know a little bit about how C# (and all other .NET languages) works and where it sits in relation to the various components that make the entire .NET Framework run.

One such component is the Common Language Runtime (almost exclusively referred to as the CLR). Unlike previous versions of C++ and similar languages, C# runs in a managed environment. Code that you write in C# runs inside the context of the Common Language Runtime. The runtime is responsible for managing things like memory and security and isolating your code from other code so that malicious or poorly written code can’t interfere with the normal operation of your application.

Figure 1.1 illustrates the layers of .NET.

Figure 1.1 The layers of .NET.

Image

At the top layer you have the various .NET languages (this figure only includes a few of the languages that run under the CLR). Beneath those languages you have the Base Class Library. The BCL (Base Class Library) is the collection of classes and utilities written in the .NET Framework that provide you with the fundamentals you need in order to create your applications, such as code to allow you to deal with encryption, data access, file I/O, web applications, Windows applications, and much more. As you will see throughout the book, much of the task of learning C# isn’t learning the language syntax; it’s learning about the vast library of the BCL. In short, the CLR is the managed execution engine that drives the code written in the BCL and any applications you create.

Don Box has written an excellent book on the Common Language Runtime that gives all the detail you can possibly imagine on what the CLR is and how it works. The book is called Essential .NET Volume I: The Common Language Runtime (ISBN 0201734117, Addison-Wesley Professional).

The Common Type System

A common problem in many programming languages is the inability to exchange data between programs written in different languages. For example, you have to take special precautions when invoking C methods from Pascal, and Pascal methods from C because of parameter ordering. In addition, strings in C consist of an array of characters that are terminated with the ASCII NULL (typically represented as ). In Pascal, the first byte of a string actually contains the length of the string. These problems are just the tip of the iceberg. As you can tell, getting different languages to communicate with each other can be a nightmarish task (and, historically, it has been).

A solution to this is to allow all of the languages to share a common representation for data types. The Common Type System provides for a common set of data types. For example, if you refer to a string in VB.NET, C#, J#, Delphi (.NET), managed C++, or any other .NET language, you are guaranteed to be referring to the same entity. This is because the type string is actually defined within the .NET Framework itself, not the language. Removing the data type definition from the languages creates an environment where VB.NET and C# code can coexist side by side without any communication issues.

Taking Out the Trash: Coding in a Garbage-Collected Environment

As I mentioned earlier in this section, the CLR does quite a bit of memory management on your behalf. If you have used C# 1.0 or 1.1, you will be familiar with this concept.

One of the components of the CLR is the Garbage Collector. When you declare new variables (we’ll get to that in the next section) in C#, they are managed by the Garbage Collector. When a collection cycle takes place, the Garbage Collector examines your variables and if they are no longer in use, it will dispose of them (referred to as a collection). In Chapter 16, “Optimizing your .NET 2.0 Code,” you will learn more about the Garbage Collector (GC) and how awareness of its presence while coding and designing can improve the speed of your applications. For now, it is good enough to know that the GC is there managing your memory and cleaning up after you and your variables.

Working with Variables in C# 2.0

My favorite analogy for explaining variables is the “bucket” analogy. Think of a variable as a bucket. Into that bucket, you can place data. Some buckets don’t care what kind of data you place in them, and other buckets have specific requirements on the type of data you can place in them. You can move data from one bucket to another. Unfortunately, the bucket analogy gets a little confusing when you take into account that one bucket can contain a little note inside that reads “see Bucket B for actual data” (you’ll read about reference types shortly in the section “Value Types vs. Reference Types”).

To declare a variable in C#, you can use the following syntax:

type variable_name;

You can initialize a variable on the same line:

type variable_name = initialization expression;

where type is a .NET type. The next section lists some of the core .NET types.

Common .NET Types

Table 1.1 shows some of the basic .NET data types. As you will see in later chapters, this is just the beginning. When you start using classes, the variety of types available to you will be virtually unlimited.

Table 1.1 Core .NET Data Types

Image

If you aren’t familiar with .NET or C#, you may be wondering what the “System” is in the data types listed in Table 1.1. .NET organizes all types into namespaces. A namespace is a logical container that provides name distinction for data types. These core data types all exist in the “System” namespace. You’ll see more namespaces throughout the book as you learn about more specific aspects of .NET.

Type Shortcuts

C# provides you with some shortcuts to make declaring some of the core data types easier. These shortcuts are simple one-word lowercase aliases that, when compiled, will still represent a core .NET type. Table 1.2 lists some data type shortcuts and their corresponding .NET types.

Table 1.2 C# Aliases for .NET Data Types

Image

Value Types vs. Reference Types

Up to this point, this chapter has just been illustrating data types in one category. Earlier in the chapter, I mentioned a “bucket” analogy where data in one bucket could actually refer to data contained in some other bucket. This is actually the core point to illustrate the difference between value types and reference types.

A value type is a type whose data is contained with the variable on the stack. Value types are generally fast and lightweight because they reside on the stack (you will read about the exceptions in Chapter 16, “Optimizing your .NET 2.0 Code”).

A reference type is a type whose data does not reside on the stack, but instead resides on the heap. When the data contained in a reference type is accessed, the contents of the variable are examined on the stack. That data then references (or points to, for those of you with traditional C and C++ experience) the actual data contained in the heap. Reference types are generally larger and slower than value types. Learning when to use a reference type and when to use a value type is something that comes with practice and experience.

Your code often needs to pass very large objects as parameters to methods. If these large parameters were passed on the stack as value types, the performance of the application would degrade horribly. Using reference types allows your code to pass a “reference” to the large object rather than the large object itself. Value types allow your code to pass small data in an optimized way directly on the stack.

C# Basic Syntax

You will learn a lot of C# syntax tricks as you progress through the book. This section introduces you to the most basic concepts required to create the simplest C# application—the canonical “Hello World” sample.

Code Blocks

As you know, all programming languages work on the same basic principle: individual instructions are executed in sequence to produce some result. Instructions can be anything from defining a class to printing information to the Console output.

In C#, multiple lines of code are grouped together into a logical execution block by wrapping the lines of code with the “curly brackets” or braces: the { and } symbols.

The Canonical “Hello World” Sample

It seems as though virtually every book on a programming language starts off with a program that prints the phrase “Hello World” to the console. Rather than risk horrible karma and unknown repercussions from breaking with tradition, I am going to inflict my own version of “Hello World” upon you.

To start, open up whatever 2005 IDE you have (C# Express 2005, or any of the Visual Studio 2005 editions) and create a new Console Application (make sure you select C# if you have multiple languages installed) called HelloWorld. Make sure that your code looks the same as the code shown in Listing 1.1.

Listing 1.1 The Hello World Application

Image

The Console class (you’ll learn about classes in Chapter 5, “Objects and Components”) provides a set of methods for dealing with the console. In previous versions of .NET, you could not do anything with colors in the Console class. With .NET 2.0, you now have the ability to change the foreground and background colors of the console.

Press Ctrl+F5 or choose Debug and then Start without Debugging. Figure 1.2 shows the output of the application, including the newly added color features of the 2.0 Console.

Figure 1.2 The Hello World Application, in full color.

Image

What You Can Do with C#

As you will see throughout this book, you can produce all kinds of applications using C#. The C# language, and the .NET Framework underneath it, allow you to create

  • Windows applications—Create compelling, fast, powerful desktop applications that can do amazing things, including update themselves over the web automatically.
  • Web applications—Create amazingly powerful, rich, full-featured web applications in the shortest amount of time ever, taking advantage of new features like Web Parts, Master Pages, Themes, and much more.
  • Web services—Get on board with Service-Oriented Architecture by exposing business logic and data over industry-standard protocols.
  • Data-driven applications—Consume data from a wide variety of sources, aggregate data from multiple sources, and expose that data to end users through Web or Windows interfaces.
  • Mobile applications—Create web applications that automatically recognize mobile platforms and adapt to the small form factor and limited capacity of PocketPCs and cellular phones.
  • Mobile clients—Create applications that target the PocketPC platform and can not only communicate with other desktop applications, but can also communicate with the Internet, consume web services, and interact with SQL databases.
  • SQL Server 2005—Create stored procedures, functions, and user-defined data types that reside directly inside the SQL Server 2005 database engine for unprecedented productivity, performance, and reliability.
  • Integration applications—Take advantage of COM Interoperability as well as .NET-based APIs to integrate your own code with other applications such as Office 2003, SharePoint Portal Server 2003, and much, much more.

Summary

This chapter provided you with a brief introduction to the world of the .NET Framework and C# 2.0. You read about how the .NET Framework evolved as well as what it is now. In addition, you were introduced to the Common Language Runtime, the Garbage Collector, the Common Type System, and finally a very small introductory application.

This chapter has provided you with the basic foundation that you will need in order to continue learning about C# 2005 by progressing through this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.41