BOOKS FOR PROFESSIONALS BY PROFESSIONALS® Rahman Expert C# 5.0 RELATED Expert C# 5.0 takes your understanding of the C# language to the next level. It close- ly examines familiar elements in forensic detail to reveal how they really work. Key language features that you already know, such as Enums, Strings, and Collections, are teased apart and examined under the twin microscopes of MSIL (Intermediate Language) and the Windbg debugger to show you what’s really going on behind the scenes as your code is compiled and passed to the CLR. Led by an expert programmer, you’ll: • Learn the detailed workings behind common language elements such as Enum, readonly, Anonymous, and Func • Understand how to work with Strings and StringBuilder in the most effective way • Master exception management far beyond the basics • See how components such as LINQ and Async interact with the C# language beneath the surface • Architect better-crafted applications that work in the most efficient and reliable way possible • Gain insight to identify and fix stubborn, hard to diagnose coding faults If you’re already experienced with writing managed applications and want to learn more about how to get the best from the language at an advanced level, then Expert C# 5.0 is the book for you. It offers a deep investigation of C#, which will enable you to become a true master of the language. Shelve in .NET User level: Advanced SOURCE CODE ONLINE www.apress.com www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info Contents at a Glance n About the Author .................................................................................................................xii n About the Technical Reviewer ...........................................................................................xiii n Acknowledgments ..............................................................................................................xiv n Chapter 1: Reintroducing C#:-A Detailed Look at the Language We All Know ...................1 n Chapter 2: C# Objects in Memory .......................................................................................85 n Chapter 3: Parameters ......................................................................................................109 n Chapter 4: Methods ...........................................................................................................137 n Chapter 5: Automatic Property Declaration......................................................................157 n Chapter 6: Enum ................................................................................................................175 n Chapter 7: Delegate ...........................................................................................................187 n Chapter 8: Event ................................................................................................................213 n Chapter 9: Foreach and Iterator ........................................................................................233 n Chapter 10: The String Data Type ....................................................................................255 n Chapter 11: Collections Explained ...................................................................................285 n Chapter 12: Linq in C# .......................................................................................................349 n Chapter 13: Exception Management .................................................................................455 n Chapter 14: Asynchrony ....................................................................................................497 n Chapter 15: Diagnostic Tools in .NET ................................................................................555 n Index ..................................................................................................................................587 iii www.it-ebooks.info Acknowledgments It has been a long journey writing this book, and I want to thank many people, especially my acquisition editor, Ewan Buckingham, from Apress, who made publication of this book possible. Every person at Apress who was involved with this book did an excellent job, and I thank them all. I would especially like to express my appreciation to my development editor, Jonathan Hassell, as well as James Markham, who gave me many great suggestions and improved the quality of the book. I also thank my copy editor, Mary Bearden, who did a great job editing this book. I also express my thanks to my coordinating editor, Katie Sullivan. Lastly and most importantly, I thank my technical editor, Todd Meister, who did a fabulous job and provided many excellent suggestions. Looking back on this year, when I was writing articles for the codeproject.com, a few members suggested that I should write a book. Especially Sander Rossel, who recommended I get in touch with Apress. Marcelo Oliveira is another member from codeproject.com who inspired me to write this book. My thanks to both Sander and Marcelo. I also give special thanks to my parents for their support and best wishes through this process. I also thank my sister and sister-in-law. Lastly, I am grateful to my wife for her support, passion, and understanding and for letting me work late nights and over weekends. xiv www.it-ebooks.info CHAPTER 1 n n n Reintroducing C#:-A Detailed Look at the Language We All Know This chapter will discuss the basics of the C# language. It begins with an example of a square number generator program to explain the basic structure of a C# program, how the C# compiles a C# program, and then explains Just-in-Time compilation. You will learn about the lexical element of the C# language, different types such as value and reference types, variables, parameters, and statements, and about the interface, enum, and delegate classes. Square Number Using the C# Listing 1-1 shows a simple program that calculates the square of a given number and displays the squared number as output. Listing 1-1. Square Number Program using System; /* importing namespace */ namespace Ch01 /* namespace declaration */ { class Program /* class declaration*/ { static void Main(string[] args) /* method declaration */ { PowerGenerator pg = new PowerGenerator(); pg.ProcessPower(); } /* end of method declaration */ } /* end of class declaration */ public class PowerGenerator { const int limit = 3; /* constant declaration */ const string original = "Original number", 1 www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW square = "Square number"; public void ProcessPower() { Console.WriteLine("{0,16}{1,20}", original, square); /* statement*/ for (int i = 0; i <= limit; ++i) /* iteration statement*/ { Console.Write("{0,10}{1,20}\n", i, Math.Pow(i, 2)); } } } } /* end of namespace declaration */ A C# program consists of statements, and each of these statements executes sequentially. In Listing 1-1, the Pow method from the Math class processes the square of a number, and the Write method from the Console class displays the processed square number on the console as output. When Listing 1-1 is compiled using the C# compiler csc.exe and executes the executable, it will produce the output: Original number Square number 0 0 1 1 2 4 3 9 Listing 1-1 contains a class called a program inside the namespace Ch01. A namespace is used to organize classes, and classes are used to organize a group of function members, which is called a method. A method is a block of statement defined inside curly braces {}, such as {statement list} inside a class, for example: static void Main( string[] args ){……} An int literal 3 and the string literals “Original number” and “Square number” are used in the program to define three variables. In Listing 1-1, the iteration statement for is used to iterate through the processing. A local variable i is declared in the for loop as a loop variable. The following section will explore the compilation process of a C# program. Compilation of a C# Program The C# compiler compiles the C# source code into the module, which is finally converted into the assembly. The assembly contains the Intermediate Language (IL) code along with the metadata information about the assembly. All of this happens in the compile time of the program. Figure 1-1 demonstrates the compilation process of a C# program. 2 www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW Figure 1-1. The compilation process of a C# program The common language runtime (CLR) works with the assembly. It loads the assembly and converts it into the native code to execute the assembly, as demonstrated in Figure 1-1. When the CLR executes a program, it executes the program method by method, and before it executes any method (unless the method has already been Jitted), the JITTER needs to convert it into the native code. The compiler refers to the Just-in-Time (JIT) compiler of the CLR, which is responsible for compiling the IL code into the native instructions for execution. The CLR retrieves the appropriate metadata information of the method from the assembly, extracts the IL code for the method, and allocates a block of memory onto the Heap, where the JITTER will store the JITTED native code for that method. The following section will explore the Jitting process to convert IL code into the native code. Jitting a C# Program Figure 1-1 shows that in runtime the JIT compiler, which is part of the CLR, compiles the IL code into the native code. Let’s analyze Listing 1-1 to see how the IL code of the method is converted into the native code. 1. Step 1: When the CLR loads the assembly produced from Listing 1-1, the methods of the Program class and PowerGenerator class will not yet be Jitted by the JITTER. In Figure 1-2, you can see that the Main method of the Program class and ProcessPower method of the PowerGenerator class has not yet been JITTED, as shown by its Not JITTED yet status. Sometime later, the JITTER converts the IL code of the Main method into the native code, and the status of the method 3 www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW description table of the Main method shows the JITTED address stored in the Heap. The contents of this address will contain the JITTED native code for the Main method. 2. Step 2: The JITTER still has not generated the native code for the ProcessPower method because the status of the ProcessPower method shows Not JITTED yet as the status and the status of the ProcessPower method shows NONE for JIT status, as described in Figure 1-2. Figure 1-2. Jitting process of the assembly in Listing 1-1 4 www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW 3. Step 3: Sometime later, the JITTER converts the IL code of the ProcessPower method into the native code and the native code is stored in the Heap. The method description table of the ProcessPower method in Figure 1-2 shows the address of the native code for the ProcessPower method. The contents of the native code that are stored in the Heap, as shown in Figure 1-2, were extracted using the following commands: !u –n 004c0050 !u –n 004c00e8 n Note: The IL code shown in Figure 1-1 was decompiled using the ildasm.exe. The windbg.exe was used to explore different runtime information while the executable from Listing 1-1 executes. You can explore more detail about the ildasm.exe and windbg.exe tools in Chapter 15. In Figure 1-2, a different debugging command used, which is also discussed in Chapter 15. In addition to the ildasm.exe and windbg.exe tools, the .NET Reflector tool is used to explore the IL/C# code for the assembly. Understanding the C# Language This section explores the C# language. You will learn the syntax and usage of the identifiers, keywords, and literals. You will explore the different types used in C#, such as value type and reference type, how to declare a variable, and how many different types of variables can be used in a program. You will also learn about different types of statements that can be declared in C#, and, finally, you will learn about classes, types of classes, constructors, fields, and methods. Identifiers Identifiers are names used in the application to identify a namespace, class, method, variable, delegate, interface, and so on. Figure 1-3 demonstrates the possible forms of the identifiers. Figure 1-3. Possible forms of the identifier declaration Figure 1-3 demonstrates the possible combination of the characters and digits used to define an identifier. • An identifier is composed of the Unicode characters or it can start with an underscore character or characters (_) along with other characters, such as _ identifier or _iden77tifier, or \u005F\u005FIdentifier (compiled as __Identifier). 5 www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW • An identifier can start with the at sign (@) as its prefix, such as @int (as used in Listing 1-2), and it is referred to as the verbatim identifier. To use a keyword as an identifier, the @ needs to be the prefix for the keyword. • Unicode escape is used to define an identifier, such as “cl\u0061ss,” when the C# compiler compiles “cl\u0061ss” as a class. Listing 1-2 shows the usage of the identifier in a program. Listing 1-2. Example of the Identifier using System; /* Ch01 is the identifier to name the namespace*/ namespace Ch01 { /* Program is the identifier to name the class */ class Program { /* Main is the identifier to name the method */ static void Main(string[] args) { /* a and _a is the identifier to name the variable */ int a = 10, _a = 20; /* Verbatim identifier - start with an @ prefix */ int @int = 10; Console.WriteLine("{0}\t{1}\t{2}", a,_a, @int); } } } This program will produce the output: 10 20 10 The decompiled IL code (decompiled using the ildasm.exe) of Listing 1-2 shows how the variable names, such as a, _a, and @int, are compiled by the C# compiler: .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 4 .locals init ( [0] int32 a, /* a compiled as a */ [1] int32 _a, /* _a compiled as _a */ [2] int32 int) /* @int compiled as int */ /* Code removed */ } The IL code shows that the variables a and _a are compiled as they are defined in the C# source code, but the @int is compiled as int, where the C# compiler eliminates the @ character from the verbatim identifier. 6 www.it-ebooks.info
Description: