Chapter 1. Introduction to Microsoft Visual C# Programming

Microsoft Visual Studio 2008, known during development as Orcas, is the successor to Microsoft Visual Studio 2005. The launch of the latest version of Visual Studio coincides with the release of Visual C# 2008, .NET Framework 3.5, and ASP.NET 3.5. Microsoft continues to shift Visual Studio from simply a comprehensive developer tool to a solution for the software lifecycle. This includes an Integrated Development Environment (IDE), components (testing tools, code analysis, and more), and tools for software design, development, testing, quality assurance, and debugging.

Anders Hejlsberg, technical fellow and chief architect of the C# language at Microsoft, has discussed Visual C# 2008 on numerous occasions. He highlights Language Integrated Query (LINQ) and related enhancements as the primary new features in Visual C# 2008. LINQ is a unified query model that is object-oriented and integrated into the C# language. New features, such as lambda expressions, extension methods, expression trees, implicitly typed local variables and objects, and other new features are useful in isolation, but they also extend the language to support LINQ. These and other changes are sure to secure the stature of C# as the preeminent development language for .NET.

With LINQ, Visual C# 2008 changes the relationship between developers and data. LINQ is an elegant solution for accessing specific data using a query language that is independent of the data source. LINQ is also object-oriented and extensible. LINQ moves C# a measure closer to functional programming, it refocuses developers from managing the nuts and bolts of data (state) to behavior of information (objects), and it provides a unified model for querying data that no longer depends on the vagaries of a specific language or technology. With LINQ, you can access with the same unified query model a Structured Query Language (SQL) database, an Extensible Markup Language (XML) file, or even an array.

LINQ removes the distinction between data and objects. Traditional queries are strings that are not entirely type-safe and return a vector of information, which defines the disconnect between data and objects (objects being type-safe, supporting IntelliSense, and not necessarily rectangular). LINQ forms an abstraction layer that allows developers to treat data as objects and focus on solutions in a unified manner without sacrificing specificity.

Visual Studio 2008 epitomizes the term unified. For example, Visual Studio 2008 provides a unified environment for developing to different .NET targets. In addition, the Visual Studio Designer provides a unified canvas where Microsoft Windows Forms, Extensible Application Markup Language (XAML), and Windows XP and Windows Vista visually themed applications can be designed and implemented. Visual Studio C# 2008 has additional capabilities for creating enterprise, distributed, or Web-based applications—most notably with Microsoft Silverlight. Silverlight is a plug-in that provides a unified environment for building Web applications with cross-browser support and that promotes enhanced rich interactive applications (RIA).

Visual Studio 2008, with ASP.NET 3.5, further separates design and implementation responsibilities, allowing for clearer separation of designer and developer roles.

The trend towards collaborative and team development continues. No developer can be completely self-reliant, and Visual Studio 2008 has additional features that benefit a wide variety of teams ranging from small to large in size. Visual Studio 2008 also recognizes the important role of everyone—not just developers but others on the software team. For example, the new database project separates language developer and database developer/architect roles.

As mentioned, Visual Studio 2008 encompasses the entire life cycle of a software application. The product boasts new revisions of tools for testing and quality assurance. Many of these tools were introduced in Visual Studio 2005. Furthermore, testing tools have been extended to the Professional revision of the product, making them available to more developers and not reserved for Microsoft Visual Studio Team editions. Both developers and non-developers, such as quality assurance staff, can use the testing tools that have been incorporated into Visual Studio 2008. The testing tools are easy to use but comprehensive, and performance also has been improved. Finally, the testing tools are integrated better, including seamless access to unit testing in the IDE. Chapter 17, reviews Visual Studio 2008 testing tools.

.NET Framework 3.5 and the Common Language Runtime (CLR) platform continues to provide important services for managed applications, such as memory management, security services, type-safety, and structured exception handling. The .NET Framework now supports LINQ and other new features. Some favorite new elements of the .NET Framework include (but are not limited to) Active Directory APIs (System.DirectoryServices.AccountManagement.dll), ASP.NET AJAX (System.Web.Extensions), Peer-To-Peer (P2P) support (System.NET.dll), STL to CLR for Managed C++ developers (System.VisualC.STLCLR.dll), Window Presentation Foundation (WPF; System.Windows.Presentation.dll), and Windows Communication Foundation (System.WorkflowServices.dll). .NET Framework 3.5 offers numerous other enhancements, including improved network layers and better performing sockets.

Visual C# 2008 is a modern, object-oriented, and type-safe programming language. C# has its roots in the C family of languages and will be immediately comfortable to C, C++, and Java programmers. The ECMA-334 standard and ISO/IEC 23270 standard apply to the C# language. Microsoft’s C# compiler for the .NET Framework is a conforming implementation of both of these standards.

A Demonstration of Visual C# 2008

To introduce programming in Visual C# 2008, the following code examples are presented with explanations. Some of the programming concepts given in this section are explained in depth throughout the remainder of the book.

Sample C# Program

In deference to Martin Richards, the creator of the Basic Combined Programming Language (BCPL) and author of the first "Hello, World!" program, I present a "Hello, World!" program. Actually, I offer an enhanced version that displays "Hello, World!" in English, Italian, or Spanish. The program is a console application.

Here is my version of the "Hello, World!" program, which is stored in a file named hello.cs:

using System;

namespace HelloNamespace {

    class Greetings{
        public static void DisplayEnglish() {
            Console.WriteLine("Hello, world!");
        }
        public static void DisplayItalian() {
            Console.WriteLine("Ciao, mondo!");
        }
        public static void DisplaySpanish() {
            Console.WriteLine("Hola, imundo!");
        }
    }

    delegate void delGreeting();

    class HelloWorld {
        static void Main(string [] args) {
            try {
                int iChoice = int.Parse(args[0]);
                delGreeting [] arrayofGreetings={
                    new delGreeting(Greetings.DisplayEnglish),
                    new delGreeting(Greetings.DisplayItalian),
                    new delGreeting(Greetings.DisplaySpanish)};

                arrayofGreetings[iChoice - 1]();
            }
            catch(Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Csc.exe is the C# compiler. Enter the following csc command at the Visual Studio command prompt to compile the hello.cs source file and create the executable hello.exe:

csc hello.cs

The hello.exe file is a .NET single-file assembly. The assembly contains metadata and Microsoft Intermediate Language (MSIL) code but not native binary. Mixed assemblies (both native and managed) may contain binary.

Run the Hello application from the command line. Enter the program name and the language (1 for English, 2 for Italian, or 3 for Spanish). For example, the following command line displays "Ciao, mondo!" ("Hello, world!" in Italian).

Hello 2

The source code of the Hello application highlights the common elements of most .NET applications: using statement directive, a namespace, types, access modifiers, methods, exception handling, and data.

Note

Note

C# is case-sensitive.

The HelloNamespace namespace contains the Greetings and HelloWorld types. The Greetings class has three static methods, and each method displays "Hello, World!" in a different natural language. Static methods are invoked on the type (classname.member), not an instance of that type. The static methods of the Greetings type are also public and therefore visible inside and outside the class.

Delegates define a type of function pointer. The delGreeting delegate is a container for function pointers. A delGreeting delegate points to functions that return void and have no parameters. This is (not so coincidentally) the function signature of the methods in the Greetings type.

The entry point of this and any other C# executable is a Main method. Command-line parameters are passed as the args parameter, which is a string array. In the HelloWorld program, the first element of the args array is used as a number indicating the language of choice, as input by the user. The Hello application converts that element to an integer. Next, the program defines an array of function pointers, which is initialized to point to each of the methods of the Greetings class. The following statement invokes a function pointer to display the selected HelloWorld message:

arrayofGreetings[iChoice - 1]();

The value iChoice - 1 is an index into the delegate array. Since arrays are zero-based in C#, iChoice is offset by -1.

Most of the code in the Main method is contained in a try block. The code in the try block is a guarded body. A guarded body is protected against exceptions defined in the corresponding catch filter. When an exception is raised that meets the criteria of the catch filter, execution is transferred to the catch block, which displays the exception message. If no exception is raised, the catch block is not executed. In our HelloWorld application, omitting the choice or entering a non-numeric command-line parameter when running the program will cause an exception, which is caught, and the catch block displays the appropriate message.

There are several statement blocks in the sample code. A statement block contains zero or more statements bracketed with curly braces {}. A single statement can be used separately or within a statement block. The following two code examples are equivalent:

// Example 1
if (bValue)
    Console.WriteLine ("information");

// Example 2
if (bValue)
{
    Console.WriteLine ("information");
}

Sample LINQ Program

Because LINQ plays such an important role in Visual C# 2008, here are two sample applications to demonstrate LINQ. Actually, the LINQ example comprises two examples: a traditional version and a LINQ version. Both examples list the names of people that are 30 years old or older. The traditional example filters the names with an if statement. The LINQ example uses a LINQ query to ascertain the correct names. The result of both applications is identical.

Here is the traditional example, stored in a file named people.cs:

using System;

namespace Example {

    class Person {
        public Person(string _name, int _age) {
            name = _name;
            age = _age;
        }
        public string name = "";
        public int age = 0;
    }
    class Startup {
        static void Main() {
            Person [] people = {new Person("John", 35),
                                new Person("Jill", 37),
                                new Person("Jack", 25),
                                new Person("Mary", 28)};
            foreach (Person p in people) {
                if (p.age >= 30) {
                    Console.WriteLine(p.name);
                }
            }
        }
    }
}

The code has a single namespace, which is Example. Example contains the Person and Startup types. The Person class has a public two-argument constructor. A constructor is a method with the same name as its class. This constructor is used to initialize instances of the Person class. The Person type contains two fields—name and age.

Main, the entry point function, is in the Startup class. In Main, an array of four employees is defined. The foreach statement iterates through the elements in the people array. Next, the if statement filters the employees and displays the names of people 30 years old or older in the console window.

The program is compiled with the C# compiler as follows:

csc people.cs

Here is the LINQ version of this example:

using System;
using System.Linq;

namespace Example {

    class Person {
        public Person(string _name, int _age) {
            name = _name;
            age = _age;
        }
        public string name = "";
        public int age = 0;
    }

    class Startup {
        static void Main() {
            Person [] people={new Person("John", 35),
                              new Person("Jill", 37),
                              new Person("Jack", 25),
                              new Person("Mary", 28)};
            var ageQuery = from p in people
                      where p.age >= 30
                      select p;
            foreach (var p in ageQuery) {
                Console.WriteLine(p.name);
            }
        }
    }
}

The LINQ version filters people using a LINQ query instead of an if statement. This highlights the seminal difference between a traditional query and LINQ. The if statement in the traditional version filters data, whereas the LINQ query in the LINQ example filters Person objects. In this way, LINQ removes the disconnect between objects and data.

The var keyword in the ageQuery variable declaration is for type inference. Type inference is not typeless. A specific type is inferred at compile time from the result of the LINQ query expression. This keeps the code type-safe, which is an important tenet of .NET. In our example, the query expression evaluates to an array of Person types. Therefore, at compile time, "var query" implies "Person [] query".

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

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