




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































*OUSPEVDUJPO
-FYJDBM4USVDUVSF
6OTBGF$PEF
" %PDVNFOUBUJPO$PNNFOUT
# (SBNNBS
$ 3FGFSFODFT
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
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#.
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;
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.
order is insignificant in C# is unlike the C++ language.
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
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).
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.
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.
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.
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.
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?
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.
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
$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
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.
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.
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.
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.
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.