C Sharp Syntax Part-2


Control structures
C# inherits most of the control structures of C/C++ and also adds new ones like the foreach statement.

Conditional structures
These structures control the flow of the program through given conditions.
if statement
The if statement is entered when the given condition is true. Single-line case statements do not require block braces although it is mostly preferred by convention.
Simple one-line statement:
if (i == 3) ... ;
Multi-line with else-block (without any braces):
if (i == 2)
    ...
else
    ...
Recommended coding conventions for an if-statement.
if (i == 3)
{
    ...
}
else if (i == 2)
{
    ...
}
else
{
    ...
}
switch statement
The switch construct serves as a filter for different values. Each value leads to a "case". Many cases may lead to the same code though. The default case handles all the other cases not handled by the construct.
switch (ch)
{
    case 'A':
        statement;
        ...
        break;
    case 'B':
        statement;
        break;
    case 'C': // A switch section can have multiple case labels.
    case 'D':
        ...
        break;
    default:
        ...
        break;
}
Loops / Iteration structures
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true.
while loop
while (i == true)
{
    ...
}
do ... while loop
do
{
   
}
while (i == true);
for loop
The for loop consists of three parts: declaration, condition and increment. Any of them can be left out as they are optional.
for (int i = 0; i < 10; i++)
{
    ...
}
Is equivalent to this code represented with a while statement, except here the i variable is not local to the loop.
int i = 0;
while (i < 10)
{
    //...
    i++;
}
foreach loop
The foreach statement is derived from the for statement and makes use of a certain pattern described in C#'s language specification in order to obtain and use an enumerator of elements to iterate over.
Each item in the given collection will be returned and reachable in the context of the code block. When the block has been executed the next item will be returned until there are no items remaining.
foreach (int i in intList)
{
    ...
}
Jump statements
Jump statements  simply represent the jump-instructions of an assembly language that controls the flow of a program.
Labels and goto statement
Labels are given points in code that can be jumped to by using the goto statement.
start:
    .......
    goto start;
The goto statement can be used in switch statements to jump from one case to another or to fall through from one case to the next.
switch(n)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        goto case 1;
    case 3:
        Console.WriteLine("Case 3");
    case 4: // Compilation will fail here as cases cannot fall through in C#.
        Console.WriteLine("Case 4");
        goto default; // This is the correct way to fall through to the next case.
    default:
        Console.WriteLine("Default");
}
break statement
The break statement breaks out of the closest loop or switch statement. Execution continues in the statement after the terminated statement, if any.
int e = 10;
for (int i = 0; i < e; i++)
{
    while (true)
    {
        break;
    }
    // Will break to this point.
}
continue statement
The continue statement discontinues the current iteration of the current control statement and begins the next iteration.
int ch;
while ((ch = Console.Read()) != -1)
{
               if (ch == ' ')
                               continue;    // Skips the rest of the while-loop

               // Rest of the while-loop
               ...
}
The while loop in the code above reads characters by calling GetChar(), skipping the statements in the body of the loop if the characters are spaces.
Exception handling
Runtime exception handling method in C# is inherited from Java and C++.
The base class library has a class called System.Exception from which all other exception classes are derived. An Exception-object contains all the information about a specific exception and also the inner exceptions that were caused. Programmers may define their own exceptions by deriving from the Exception class.
An exception can be thrown this way:
    throw new NotImplementedException();
try ... catch ... finally statements
Exceptions are managed within try ... catch blocks.
try
{
    // Statements which may throw exceptions
    ...
}
catch (Exception ex)
{
    // Exception caught and handled here
    ...
}
finally
{
    // Statements always executed after the try/catch blocks
    ...
}
Either a catch block, a finally block, or both, must follow the try block.
Types
C# is a statically typed language like C and C++. That means that every variable and constant gets a fixed type when it is being declared. There are two kinds of types: value types and reference types.
Value types
Instances of value types reside on the stack, i.e. they are bound to their variables. If you declare a variable for a value type the memory gets allocated directly. If the variable gets out of scope the object is destroyed with it.
Structures
Structures are more commonly known as structs. Structs are user-defined value types that are declared using the struct keyword. They are very similar to classes but are more suitable for lightweight types. Some important syntactical differences between a class and a struct are presented later in this article.
struct AAA
{
    ...
}
The primitive data types are all structs.
Pre-defined types
These are the primitive datatypes.
Data Type
Description
   Nanespace Class
Range
bool
Boolean value
System.Boolean
True or False
byte
8-bit unsigned integer
System.Byte
0 to 255
char
16-bit Unicode character
System.Char
U +0000 to U +ffff
decimal
128-bit precise decimal values with 28-29 significant digits
System.Decimal
(-7.9 x 1028 to 7.9 x 1028) / 100 to 28
double
64-bit double-precision floating point type
System.Double
(+/-)5.0 x 10-324 to (+/-)1.7 x 10308
float
32-bit single-precision floating point type
System.Single
-3.4 x 1038 to + 3.4 x 1038
int
32-bit signed integer type
System.Int32
-2,147,483,648 to 2,147,483,647
long
64-bit signed integer type
System.Int64
-923,372,036,854,775,808 to 9,223,372,036,854,775,807
sbyte
8-bit signed integer type
System.Sbyte
-128 to 127
short
16-bit signed integer type
System.Int16
-32,768 to 32,767
uint
32-bit unsigned integer type
System.UInt32
0 to 4,294,967,295
ulong
64-bit unsigned integer type
System.UInt64
0 to 18,446,744,073,709,551,615
ushort
16-bit unsigned integer type
System.UInt16
0 to 65,535

Enumerations
Enumerated types (enums) are named values representing integer values.
enum Season
{
    Winter = 0,
    Spring = 1,
    Summer = 2,
    Autumn = 3,
    Fall = Autumn    // Autumn is called Fall in American English.
}

Reference types
Variables created for reference types are typed managed references. When the constructor is called, an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope the reference is broken and when there are no references left the object gets marked as garbage. The garbage collector will then soon collect and destroy it.
A reference variable is null when it does not reference any object.
Arrays
An array type is a reference type that refers to a space containing one or more elements of a certain type. All array types derive from a common base class, System.Array. Each element is referenced by its index just like in C++ and Java.
An array in C# is what would be called a dynamic array in C++.
int[] numbers = new int[2];
numbers[0] = 2;
numbers[1] = 5;
int x = numbers[0];
Initializers
Array initializers provide convenient syntax for initialization of arrays.
// Long syntax
int[] numbers = new int[5]{ 20, 1, 42, 15, 34 };
// Short syntax
int[] numbers2 = { 20, 1, 42, 15, 34 };
// Inferred syntax
var numbers3 = new[] { 20, 1, 42, 15, 34 };
Multi-dimensional arrays
Arrays can have more than one dimension, for example 2 dimensions to represent a grid.
int[,] numbers = new int[3, 3];
numbers[1,2] = 2;

int[,] numbers2 = new int[3, 3] { {2, 3, 2}, {1, 2, 6}, {2, 4, 5} };

Comments