Beruflich Dokumente
Kultur Dokumente
if statement
if (expression)
statement1
[else
statement2]
switch
switch (expression)
{
case constant-expression:
statement
jump-statement
[default: statement]
}
Do Loop
do
{
Console.WriteLine( "i: {0}", i );
i++;
} while ( i < 10 );
For loop
for ( int i = 0; i < 100; i++ )
{
Console.Write( "{0} ", i );
if ( i % 10 == 0 )
{
Console.WriteLine( "\t{0}", i );
}
}
return ;
}
The continue statement causes the loop to skip the remaining steps in the loop and
returns to the top of a loop
The foreach statement is used for looping through the elements of an array or a
collection.
Defining Classes
To create a new class, you first declare it, and then define its methods and fields. You
declare a class using the class keyword. The complete syntax is as follows:
[attributes] [access-modifiers] class identifier [:[base-class [,interface(s)]]
{class-body}
Table 4-1. Access modifiers
Method Arguments
Methods can take any number of parameters.* The parameter list follows the method
name and is enclosed in parentheses, with each parameter preceded by its type.
void MyMethod (int firstParam, Button secondParam)
{
// ...
}
Creating Objects
The primitive C# types (int, char, etc.) are value types and are created on the stack.
Objects,
however, are reference types and are created on the heap, using the keyword new,
as
in the following:
Time t = new Time( );
constructor
In fact, a method is invoked whenever you instantiate an object. This method is
called a constructor, and you must either define one as part of your class definition,
or let the CLR provide one on your behalf. The job of a constructor is to create the
object specified by a class and to put it into a valid state. Before the constructor runs,
the object is undifferentiated memory; after the constructor completes, the memory
holds a valid instance of the class type
Static methods act more or less like global methods, in that you can invoke them
without actually having an instance of the object at hand.
If your class declares a static constructor, you are guaranteed that the static
constructor
will run before any instance of your class is created.*
Destroying Objects
Because C# provides garbage collection, you never need to explicitly destroy your
objects. However, if your object controls unmanaged resources, you will need to
explicitly free those resources when you are done with them. Implicit control over
unmanaged resources is provided by a destructor, which will be called by the
garbage
collector when your object is destroyed.
The using statement also protects you against unanticipated exceptions. Regardless
of how control leaves the using statement, Dispose( ) is called. An implicit tryfinally
block is created for you.
Readonly Fields
public static int Year;
Abstract Classes
An abstract method has no implementation. It creates a method name and signature
that must be implemented in all derived classes. it is not legal to instantiate
an object of an abstract class
A sealed class doesn’t allow classes to derive from it at all. Placed before the class
declaration,
the sealed keyword precludes derivation. Classes are most often marked
sealed to prevent accidental inheritance.
The syntax for declaring a struct is almost identical to that for a class:
[attributes] [access-modifiers] struct identifier [:interface-list]
{ struct-members
Unlike classes, structs don’t support inheritance. They implicitly derive from Object
(as do all types in C#, including the built-in types), but can’t inherit from any other
class or struct. Structs are also implicitly sealed (i.e., no class or struct can derive
from a struct). Like classes, however, structs can implement multiple interfaces.
Additional differences include the following: No destructor or custom default
constructor You can’t initialize an instance field in a struct.
Interface Purpose
ICollection<T> Base interface for generic collections
IEnumerator<T> Enumerate through a collection using a foreach
ICollection<T> Implemented by all collections to provide the CopyTo( ) method as well
as the Count,
IsSynchronized, and SyncRoot properties
IComparer<T>
IComparable<T> Compare two objects held in a collection so that the collection can be
sorted
IList<T> Used by array-indexable collections
IDictionary<K,V> Used for key-/value-based collections such as Dictionary
List<T>
The classic problem with the Array type is its fixed size.
The List class is an array whose size is dynamically increased as required
When you create a List, you don’t define how many objects it will contain. You add
to the List using the Add( ) method, and the list takes care of its own internal
bookkeeping
The List has a property, Capacity,
which is the number of elements that the List is capable of storing
A queue represents a first-in, first-out (FIFO) collection. queue is a good collection to
use when you are managing a limited resource. For
example, you might want to send messages to a resource that can handle only one
message at a time
Method or property Purpose
Count Public property that gets the number of elements in the Queue
Clear( ) Removes all objects from the Queue
Contains( ) Determines whether an element is in the Queue
CopyTo( ) Copies the Queue elements to an existing one-dimensional array
Dequeue( ) Removes and returns the object at the beginning of the Queue
Enqueue( ) Adds an object to the end of the Queue
GetEnumerator( ) Returns an enumerator for the Queue
Peek( ) Returns the object at the beginning of the Queue without removing it
ToArray( ) Copies the elements to a new array
TrimExcess( ) Reduces the current queue’s capacity to the actual number of elements in the list
Stacks
A stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table
or a stack of coins on your desk. An item added on top is the first item you take off
the stack.
The principal methods for adding to and removing from a stack are Push( ) and Pop( );
Stack also offers a Peek( ) method, very much like Queue. Table 9-5 shows the
significant
methods and properties for Stack.
Dictionaries
A dictionary is a collection that associates a key to a value.
Strings
Strings can also be created using verbatim string literals, which start with the at (@)
symbol. This tells the String constructor that the string should be used verbatim,
even if it spans multiple lines or includes escape characters. In a verbatim string
literal, backslashes and the characters that follow them are simply considered
additional
characters of the string.
The String type provides an overloaded Substring( ) method for extracting substrings
from within strings. Both versions take an index indicating where to begin the
extraction, and one of the two versions takes a second index to indicate where to end
the operation
A bug is a programmer mistake that should be fixed before the code is shipped.
An error is caused by user action. For example, the user might enter a number
where
a letter is expected. Once again, an error might cause an exception, but you can
prevent
that by catching errors with validation code. Whenever possible, errors should
be anticipated and prevented.
Attributes are a mechanism for adding metadata, such as compiler instructions and
other data about your data, methods, and classes to the program itself. Attributes
are
inserted into the metadata and are visible through ILDASM and other
metadatareading
tools.
Reflection is the process by which a program can read its own metadata, or metadata
from another program