Sie sind auf Seite 1von 7

A constant is an object whose value can’t be changed

Const int Freezing Point = 32; //

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.

The Ternary Operator


conditional-expression ? expression1 : expression2
This operator evaluates a conditional expression (an expression that returns a value
of
type bool), and then returns the value of either expression1 if the value returned from
the conditional expression is true, or expression2 if the value returned is false

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

Access modifier Restrictions


public No restrictions. Members marked public are visible to any method of any class.
private The members in class A that are marked private are accessible only to methods
of class A.
protected The members in class A that are marked protected are accessible to methods of
class A and
to methods of classes derived from class A.
internal The members in class A that are marked internal are accessible to methods of
any class in
A’s assembly.
protected internal The members in class A that are marked protected internal are accessible to
methods of
class A, to methods of classes derived from class A, and to any class in A’s assembly. This is
effectively
protected OR internal. (There is no concept of protected AND internal.)

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

The this Keyword


The keyword this refers to the current instance of an object.

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


To make it easier for your clients to properly dispose of your objects, C# provides a
using statement that ensures that Dispose( ) will be called at the earliest possible
time. The idiom is to declare the objects you are using and then to create a scope for
these objects with curly braces. When the closing brace is reached, the Dispose( )
method will be called on the object automatically,
using ( Font theFont = new Font( "Arial", 10.0f ) )
{
// use theFont
} // compiler will call Dispose on theFont

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.

C# imposes definite assignment, which requires that all variables be assigned a


value
before they are used. C# provides the out parameter modifier for this situation. The
out modifier removes the requirement that a reference parameter be initialized

Encapsulating Data with Properties


Properties allow clients to access class state as though they were accessing member
fields directly, while actually implementing that access through a class method. The
class designer, however, wants to hide the internal state of his class in class
members, and provide indirect access through a method.
public int Hour
{
get
{
return hour;
}
set
{
hour = value;
}
}

Readonly Fields
public static int Year;

Creating Polymorphic Methods


To create a method that supports polymorphism, you need only mark it as virtual in
its base class. Now, each derived class is free to implement its own version of
DrawWindow( ). To do so, simply override the base class virtual method by using the
keyword override in
the derived class method definition, and then add the new code for that overridden
method

C# prevents this confusion. In C#, a virtual function is always considered to be the


root of virtual dispatch; that is, once C# finds a virtual method, it looks no further
up the inheritance hierarchy. To remove the warning, the programmer must indicate
what he intends. He can mark the ListBox Sort( ) method with new, to indicate that it is
not an override of the virtual method in Control:

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.

A struct is a simple user-defined type, a lightweight alternative to a class. Structs


are
similar to classes in that they may contain constructors, properties, methods, fields,
operators, nested types, and indexers (see Chapter 9).
There are also significant differences between classes and structs. For instance,
structs don’t support inheritance or destructors. More important, although a class is
a reference type, a struct is a value type.

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.

An array is an indexed collection of objects, all of the same type


int[] myIntArray;
C# arrays are reference types, created on the heap. Thus, the array to which
myIntArray refers is allocated on the heap. The elements of an array are allocated
based on their own type. in C#, the value of the size of the array
marks the number of elements in the array, not the upper boundWhen you create an array
of value types, each element initially contains the default
value for the type stored in the array
programmers. The foreach statement allows you to iterate
through all the items in an array or other collection, examining each item in turn.
The syntax for the foreach statement is:
foreach (type identifier in expression) statement

params keyword allows you to pass in a variable number of parameters without


necessarily
explicitly creating the array.

C# supports two types of multidimensional arrays: rectangular and jagged. In a


rectangular
array, every row is the same length. A jagged array, however, is an array of
arrays, each of which can be a different length.
You can convert one array into another, if the dimensions of the two arrays are
equal, and if a conversion is possible between the reference element types.
Two useful staticmethods of Array are Sort( ) and Reverse( ). These are fully supported
for arrays of the built-in C# types such as string

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.

Chars The string indexer


Compare( ) Overloaded public static method that compares two strings
CompareTo( ) Compares this string with another
Concat( ) Overloaded public static method that creates a new string from one or more strings
Copy( ) Public static method that creates a new string by copying another
CopyTo( ) Copies the specified number of characters to an array of Unicode characters
Empty Public static field that represents the empty string
EndsWith( ) Indicates whether the specified string matches the end of this string
Equals( ) Overloaded public static and instance method that determines whether two strings
have the same value
Format( ) Overloaded public static method that formats a string using a format specification
Join( ) Overloaded public static method that concatenates a specified string between each
element of a string
array
Length The number of characters in the instance
Split( ) Returns the substrings delimited by the specified characters in a string array
StartsWith( ) Indicates whether the string starts with the specified characters
Substring( ) Retrieves a substring
ToUpper( ) Returns a copy of the string in uppercase
Trim( ) Removes all occurrences of a set of specified characters from the beginning and end of
the string
TrimEnd( ) Behaves like Trim( ), but only at the end

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

An exception is an object that encapsulates information about an unusual


program occurrence

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.

An exception handler is a block of code designed to handle the exception you’ve


thrown. Exception handlers are implemented as catch statements. Ideally, if the
exception
is caught and handled, the program can fix the problem and continue. Even if
your program can’t continue, by catching the exception, you have an opportunity to
print a meaningful error message and terminate gracefully

Metadata is information about the data—that is, information


about the types, code, assembly, and so forth—stored along with your program.

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

Das könnte Ihnen auch gefallen