Docsity

A Complete Guide to Programming in C#, Slides of Computer Science

Partial preview of the text

Download A Complete Guide to Programming in C# and more Slides Computer Science in PDF only on Docsity!

5IF$1SPHSBNNJOH-BOHVBHF

'PVSUI&EJUJPO

Mr Oddo

W

Contents

Foreword xi

Preface xiii

About the Authors xv

About the Annotators xvii

 *OUSPEVDUJPO 

 Hello, World 3

 Program Structure 4

 Types and Variables 6

 Expressions 13

 Statements 16

 Classes and Objects 21

 Structs 50

 Arrays 53

 Interfaces 56

 Enums 58

 Delegates 60

 Attributes 61

 -FYJDBM4USVDUVSF 

 Programs 65

 Grammars 65

 Lexical Analysis 67

 Tokens 71

 Preprocessing Directives 85

WJJ

$POUFOUT

WJJJ

$POUFOUT

Y

$POUFOUT

 6OTBGF$PEF 

 Unsafe Contexts 710

 Pointer Types 713

 Fixed and Moveable Variables 716

 Pointer Conversions 717

 Pointers in Expressions 720

 The fixed Statement 728

 Fixed-Size Buffers 733

 Stack Allocation 736

 Dynamic Memory Allocation 738

" %PDVNFOUBUJPO$PNNFOUT 

" Introduction 741

" Recommended Tags 743

" Processing the Documentation File 754

" An Example 760

# (SBNNBS 

# Lexical Grammar 767

# Syntactic Grammar 777

# Grammar Extensions for Unsafe Code 809

$ 3FGFSFODFT 

Index 815

 Introduction

C# (pronounced “See Sharp”) is a simple, modern, object-oriented, and type-safe program- ming language. C# has its roots in the C family of languages and will be immediately familiar to C, C++, and Java programmers. C# is standardized by ECMA International as the ECMA-334 standard and by ISO/IEC as the ISO/IEC 23270 standard. Microsoft’s C# compiler for the .NET Framework is a conforming implementation of both of these standards.

C# is an object-oriented language, but C# further includes support for component-oriented programming. Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality. Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation. C# provides language constructs to directly support these concepts, making C# a very natural language in which to create and use software components.

Several C# features aid in the construction of robust and durable applications: Garbage collection automatically reclaims memory occupied by unused objects; exception handling provides a structured and extensible approach to error detection and recovery; and the type-safe design of the language makes it impossible to read from uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts.

C# has a unified type system. All C# types, including primitive types such as int and double, inherit from a single root object type. Thus all types share a set of common opera- tions, and values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C# supports both user-defined reference types and value types, allowing dynamic allocation of objects as well as in-line storage of lightweight structures.

To ensure that C# programs and libraries can evolve over time in a compatible manner, much emphasis has been placed on versioning in C#’s design. Many programming lan- guages pay little attention to this issue. As a result, programs written in those languages break more often than necessary when newer versions of dependent libraries are intro- duced. Aspects of C#’s design that were directly influenced by versioning considerations include the separate virtual and override modifiers, the rules for method overload reso- lution, and support for explicit interface member declarations.

  )FMMP 8PSME

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

 )FMMP 8PSME

The “Hello, World” program is traditionally used to introduce a programming language. Here it is in C#:

using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); } }

C# source files typically have the file extension .cs. Assuming that the “Hello, World” program is stored in the file hello.cs, the program can be compiled with the Microsoft C# compiler using the command line

csc hello.cs

which produces an executable assembly named hello.exe. The output produced by this application when it is run is

Hello, World

The “Hello, World” program starts with a using directive that references the System namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the System namespace contains a number of types, such as the Console class referenced in the pro- gram, and a number of other namespaces, such as IO and Collections. A using directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the using directive, the program can use Console.WriteLine as shorthand for System.Console.WriteLine.

The Hello class declared by the “Hello, World” program has a single member, the method named Main. The Main method is declared with the static modifier. While instance meth- ods can reference a particular enclosing object instance using the keyword this , static methods operate without reference to a particular object. By convention, a static method named Main serves as the entry point of a program.

The output of the program is produced by the WriteLine method of the Console class in the System namespace. This class is provided by the .NET Framework class libraries, which, by default, are automatically referenced by the Microsoft C# compiler. Note that C# itself does not have a separate runtime library. Instead, the .NET Framework is the runtime library of C#.

 *OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

NN #3"%"#3".4 It is interesting to note that Console.WriteLine() is simply a

shortcut for Console.Out.WriteLine. Console.Out is a property that returns an imple- mentation of the System.IO.TextWriter base class designed to output to the console. The preceding example could be written equally correctly as follows: using System; class Hello { static void Main() { Console.Out.WriteLine("Hello, World"); } } Early in the design of the framework, we kept a careful eye on exactly how this section of the C# language specification would have to be written as a bellwether of the com- plexity of the language. We opted to add the convenience overload on Console to make “Hello, World” that much easier to write. By all accounts, it seems to have paid off. In fact, today you find almost no calls to Console.Out.WriteLine().

 1SPHSBN4USVDUVSF The key organizational concepts in C# are programs , namespaces , types , members , and assemblies. C# programs consist of one or more source files. Programs declare types, which contain members and can be organized into namespaces. Classes and interfaces are exam- ples of types. Fields, methods, properties, and events are examples of members. When C# programs are compiled, they are physically packaged into assemblies. Assemblies typi- cally have the file extension .exe or .dll, depending on whether they implement applica- tions or libraries.

The example using System; namespace Acme.Collections { public class Stack { Entry top; public void Push(object data) { top = new Entry(top, data); } public object Pop() { if (top == null) throw new InvalidOperationException(); object result = top.data;

 *OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

Console.WriteLine(s.Pop()); Console.WriteLine(s.Pop()); Console.WriteLine(s.Pop()); } }

If the program is stored in the file test.cs, when test.cs is compiled, the acme.dll assem- bly can be referenced using the compiler’s /r option: csc /r:acme.dll test.cs

This creates an executable assembly named test.exe, which, when run, produces the fol- lowing output: 100 10 1

C# permits the source text of a program to be stored in several source files. When a multi- file C# program is compiled, all of the source files are processed together, and the source files can freely reference one another—conceptually, it is as if all the source files were con- catenated into one large file before being processed. Forward declarations are never needed in C# because, with very few exceptions, declaration order is insignificant. C# does not limit a source file to declaring only one public type nor does it require the name of the source file to match a type declared in the source file.

NN &3$-11&35 This is unlike the Java language. Also, the fact that the declaration

order is insignificant in C# is unlike the C++ language.

NN $)3*44&--4 Notice in the previous example the using Acme.Collections

statement, which looks like a C-style #include directive, but isn’t. Instead, it’s merely a naming convenience so that when the compiler encounters the Stack, it has a set of namespaces in which to look for the class. The compiler would take the same action if this example used the fully qualified name: Acme.Collections.Stack s = new Acme.Collections.Stack();

 5ZQFTBOE7BSJBCMFT There are two kinds of types in C#: value types and reference types. Variables of value types directly contain their data, whereas variables of reference types store references to their data, the latter being known as objects. With reference types, it is possible for two

  5ZQFTBOE7BSJBCMFT

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

variables to reference the same object and, therefore, possible for operations on one vari- able to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).

NN +0/4,&&5 The choice of the word “reference” for reference types is perhaps

unfortunate. It has led to huge amounts of confusion (or at least miscommunication) when considering the difference between pass-by-reference and pass-by-value seman- tics for parameter passing.

The difference between value types and reference types is possibly the most important point to teach C# beginners: Until that point is understood, almost nothing else makes sense.

NN &3$-11&35 Probably the most common misconception about value types is

that they are “stored on the stack,” whereas reference types are “stored on the heap.” First, that behavior is an implementation detail of the runtime, not a fact about the language. Second, it explains nothing to the novice. Third, it’s false: Yes, the data asso- ciated with an instance of a reference type is stored on the heap, but that data can include instances of value types and, therefore, value types are also stored on the heap sometimes. Fourth, if the difference between value and reference types was their stor- age details, then the CLR team would have called them “stack types” and “heap types.” The real difference is that value types are copied by value, and reference types are copied by reference; how the runtime allocates storage to implement the lifetime rules is not important in the vast majority of mainline programming scenarios.

NN #*--8"(/&3 C# forces you to make the important decision of value semantics

versus reference semantics for your types. Developers using your type do not get to make that decision on each usage (as they do in C++). You need to think about the usage patterns for your types and make a careful decision between these two kinds of types.

NN 7-"%.33&4)&5/*,07 C# also supports unsafe pointer types, which are

described at the end of this specification. They are called “unsafe” because their neg- ligent use can break the type safety in a way that cannot be caught by the compiler.

  5ZQFTBOE7BSJBCMFT

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

NN +0/4,&&5 Hooray for byte being an unsigned type! The fact that in Java a byte

is signed (and with no unsigned equivalent) makes a lot of bit-twiddling pointlessly error-prone.

It’s quite possible that we should all be using uint a lot more than we do, mind you: I’m sure many developers reach for int by default when they want an integer type. The framework designers also fall into this category, of course: Why should String.Length be signed?

NN &3$-11&35 The answer to Jon’s question is that the framework is designed to

work well with the Common Language Specification (CLS). The CLS defines a set of basic language features that all CLS-compliant languages are expected to be able to consume; unsigned integers are not in the CLS subset.

The two floating point types, float and double , are represented using the 32-bit single- precision and 64-bit double-precision IEEE 754 formats.

The decimal type is a 128-bit data type suitable for financial and monetary calculations.

NN +0/4,&&5 These two paragraphs imply that decimal isn’t a floating point type.

It is—it’s just a floating decimal point type, whereas float and double are floating binary point types.

C#’s bool type is used to represent boolean values—values that are either true or false.

Character and string processing in C# uses Unicode encoding. The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units.

The following table summarizes C#’s numeric types.

$BUFHPSZ #JUT 5ZQF 3BOHF1SFDJTJPO

Signed integral

8 sbyte –128...

16 short –32,768...32,

32 int^ –2,147,483,648...2,147,483,

64 long –9,223,372,036,854,775,808...9,223,372,036,854,775,

Continued

 *OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

$BUFHPSZ #JUT 5ZQF 3BOHF1SFDJTJPO

Unsigned integral

8 byte 0...

16 ushort^ 0...65,

32 uint^ 0...4,294,967,

64 ulong 0...18,446,744,073,709,551,

Floating point

32 float 1.5 × 10 −^45 to 3.4 × 1038 , 7-digit precision

64 double^ 5.0 × 10 −^324 to 1.7 × 10308 , 15-digit precision

Decimal 128 decimal 1.0 × 10 −^28 to 7.9 × 1028 , 28-digit precision

NN $)345"//"(&- One of the problems we had with C++ on different platforms

is that the standard doesn’t define the number of bits used with short, int, and long. The standard defines only short <= int <= long , which results in different sizes on 16-, 32-, and 64-bit platforms. With C#, the length of numeric types is clearly defined, no matter which platform is used.

C# programs use type declarations to create new types. A type declaration specifies the name and the members of the new type. Five of C#’s categories of types are user-definable: class types, struct types, interface types, enum types, and delegate types.

A class type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Class types support single inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

NN &3$-11&35 Choosing to support single rather than multiple inheritance on

classes eliminates in one stroke many of the complicated corner cases found in mul- tiple inheritance languages.

A struct type is similar to a class type in that it represents a structure with data members and function members. However, unlike classes, structs are value types and do not require heap allocation. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

 *OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

NN &3$-11&35 In C# 1.0, we had nullable reference types and non-nullable value

types. In C# 2.0, we added nullable value types. But there are no non-nullable refer- ence types. If we had to do it all over again, we probably would bake nullability and non-nullability into the type system from day one. Unfortunately, non-nullable refer- ence types are difficult to add to an existing type system that wasn’t designed for them. We get feature requests for non-nullable reference types all the time; it would be a great feature. However, code contracts go a long way toward solving the problems solved by non-nullable reference types; consider using them if you want to enforce non-nullability in your programs. If this subject interests you, you might also want to check out Spec#, a Microsoft Research version of C# that does support non-nullable reference types.

C#’s type system is unified such that a value of any type can be treated as an object. Every type in C# directly or indirectly derives from the object class type, and object is the ulti- mate base class of all types. Values of reference types are treated as objects simply by view- ing the values as type object. Values of value types are treated as objects by performing boxing and unboxing operations. In the following example, an int value is converted to object and back again to int. using System; class Test { static void Main() { int i = 123; object o = i; // Boxing int j = (int)o; // Unboxing } }

When a value of a value type is converted to type object , an object instance, also called a “box,” is allocated to hold the value, and the value is copied into that box. Conversely, when an object reference is cast to a value type, a check is made that the referenced object is a box of the correct value type, and, if the check succeeds, the value in the box is copied out.

C#’s unified type system effectively means that value types can become objects “on demand.” Because of the unification, general-purpose libraries that use type object can be used with both reference types and value types.

There are several kinds of variables in C#, including fields, array elements, local variables, and parameters. Variables represent storage locations, and every variable has a type that determines what values can be stored in the variable, as shown by the following table.

  &YQSFTTJPOT

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

*OUSPEVDUJPO

5ZQFPG7BSJBCMF 1PTTJCMF$POUFOUT

Non-nullable value type

A value of that exact type

Nullable value type A null value or a value of that exact type

object A null reference, a reference to an object of any reference type, or a reference to a boxed value of any value type

Class type A null reference, a reference to an instance of that class type, or a reference to an instance of a class derived from that class type

Interface type A null reference, a reference to an instance of a class type that implements that interface type, or a reference to a boxed value of a value type that implements that interface type

Array type A null reference, a reference to an instance of that array type, or a reference to an instance of a compatible array type

Delegate type A null reference or a reference to an instance of that delegate type

 &YQSFTTJPOT

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. Examples of operators include + , -­‐ , *, /, and new. Examples of operands include literals, fields, local variables, and expressions.

When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the + operator.

NN &3$-11&35 Precedence controls the order in which the operators are executed,

but not the order in which the operands are evaluated. Operands are evaluated from left to right, period. In the preceding example, x would be evaluated, then y, then z, then the multiplication would be performed, and then the addition. The evaluation of operand x happens before that of y because x is to the left of y; the evaluation of the multiplication happens before the addition because the multiplication has higher precedence.

Most operators can be overloaded. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.