C# Language Fundamentals

C# and .NET Programming demonstrates a very simple C# program that prints the text string "Hello World!" to the console screen and provides a line-by-line analysis of that program. However, even that simple program was complex enough that we had to skip some of the details. In this chapter, we'll begin an in-depth exploration of the syntax and structure of the C# language. The syntax of a language is the order of the keywords, where you put semicolons, and so forth. The semantics are what you are expressing in the code, and how your code fits together. Syntax is trivial and unimportant, but because compilers are absolute sticklers for correct syntax, novice programmers pay a lot of attention to syntax until they are comfortable. Fortunately, Visual Studio 2008 makes managing syntax much easier so that you can focus on semantics, which are far more important.

In this chapter, we'll introduce statements and expressions, the building blocks of any program. You'll learn about variables and constants, which let you store values for use in your program. We'll also begin an explanation of types, and we'll take a look at strings, which you saw briefly in the Hello World program. This is all very basic stuff, but it's the foundation you need to start getting fancy. Without variables, your applications can't actually process any data. All variables need types, and variables are used in expressions. You'll see how neatly this all fits together.

Basic Data Types and their mapping to CTS (Common Type System)

There are two kinds of data type in C#.

  • Value Type (implicit data types, structs and enumeration).
  • Reference Type (objects, delegates).

value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit datatypes are defined in the language core by the language vendor, while explicit data types are types that are by using or composing implicit data types.

As we saw in the first issue, implicit data types in .Net compliant languages are mapped to types

in the Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in C# has its corresponding .Net type. The implicit data types in C# are:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375431771024/about/philosophy/2-c-language-fundamentals/asdf.bmp

Implicit data types are represented in language using keywords, so each of the above is a keyword in C#

(Keyword are the words defined by the language and can not be used as identifiers). It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#. The last point about implicit data types is that they are value types and thus stored on the stack, while user defined types or referenced types are stored using the heap. A stack is a data structure that store items in a first out (FIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. A heap consists of memory available to the program at run time. Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non-referenced data in heap during the execution of program and return that space to Operating System.

Variables

During the execution of a program, data is temporarily stored in memory. A variable is the name given to a memory location holding a particular type of data. So, each variable has associated with it a data type and a value.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375432863551/about/philosophy/2-c-language-fundamentals/wqer.bmp

e.g.,

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375433036632/about/philosophy/2-c-language-fundamentals/az.bmp

The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be referred to in the rest of program by the identifier 'i'. You can initialize the variable as you declare it (on the fly) and can also declare/initialize multiple variable of the same type in a single statement, e.g.,

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375435079468/about/philosophy/2-c-language-fundamentals/az1.bmp

In C# (like other modern languages), you must declare variables before using them. Also, there is the concept of "Definite Assignment" in C# which says "local variables (variables defined in a method) must be initialized before being used". The following program won't compile:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375435734413/about/philosophy/2-c-language-fundamentals/az12.bmp

but, if you un-comment the 2nd line, the program will compile. C# does not assign default values to local variables. C# is also a type safe language, i.e., values of particular data can only be stored in their respective (or compatible) data type. You can't store integer values in Boolean data types like we used to do in C/C++.

Constant Variables or Symbols

Constants are variables whose values, once defined, can not be changed by the program. Constant

variables are declare using the const keyword, like:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375514845310/-2-c-language-fundamentals-1/32rue.bmp

Constant variables must be initialized as they are declared. It is a syntax error to write:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375515039246/-2-c-language-fundamentals-1/32rued.bmp

It is conventional to use capital letters when naming constant variables.

Naming Conventions for variables and methods

Microsoft suggests using Camel Notation (first letter in lowercase) for variables and Pascal Notation

(first letter in uppercase) for methods. Each word after the first word in the name of both variables

and methods should start with a capital letter. For example, variable name following Camel notation

could be:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375515319839/-2-c-language-fundamentals-1/2123.bmp

Some typical names of method following Pascal Notation are

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375515483982/-2-c-language-fundamentals-1/gf.bmp

Although it is not mandatory to follow this convention, it is highly recommended that you strictly follow the convention. Microsoft no longer supports Hungarian notation, like using iMarks for integer variable. Also, using the underscore _ in identifiers is not encouraged.

Operators in C#

Arithmetic Operators

Several common arithmetic operators are allowed in C#.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375523138992/-2-c-language-fundamentals-1/12.png

The program blow uses these operators.

using System;

using System.Collections.Generic;

using System.Text;

namespace CSharpProgramming

{

class ArithmeticOperators

{

    // The program shows the use of arithmetic operators

    // + - * / % ++ --

    static  void  Main(string [] args)

    {

        // result of addition, subtraction,

        // multiplication and modulus operator

        int sum = 0, difference = 0, product = 0, modulo = 0;

        float quotient = 0;  // result of division

        int num1 = 20, num2 = 4;  // operand variables

        sum            = num1 + num2;

        difference   = num1 - num2;

        product       = num1 * num2;

        quotient      = num1 / num2;

        // remainder of 3/2

        modulo        = 3 % num2;

        Console.WriteLine("num1 = {0}, num2 = {1}",num1,num2,sum);

        Console.WriteLine("Difference of {0} and {1} is {2}", num1, num2,difference);

        Console.WriteLine(" Product   of {0} and {1} is {2}", num1, num2,product);

        Console.WriteLine(" Quotient  of {0} and {1} is {2}", num1, num2,quotient);

        Console.WriteLine();

        Console.WriteLine("Remainder when 3 is divided by {0} is {1}",num2,modulo);

        num1++;  // increment num1 by 1

        num2--;  // decrement num2 by 1

        Console.WriteLine("num1 = {0}, num2 = {1}",num1,num2);

    }

}

}

Although the program above is quite simple, I would like to discuss some concepts here. In the

Console. WriteLine() method, we have used format-specifiers {int} to indicate the position of variables

in the string.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375524150676/-2-c-language-fundamentals-1/a.bmp

Here, {0}, {1} and {2} will be replaced by the values of the num1, num2, and sum variables. In {i}, ispecifier that (i+1)th variable after double quotes will replace it when printed to the Console. Hence,{0} will be replaced by the first one, {1} will be replaced by the second variable and so on...

Another point to note is that num1++ has the same meaning as:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375524567172/-2-c-language-fundamentals-1/g.bmp

Or:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375524699106/-2-c-language-fundamentals-1/14.bmp

(We will see the description of second statement shortly)

Prefix and Postfix notation

Both the ++ and -- operator can be used as prefix or postfix operators. In prefix form:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375526458348/-2-c-language-fundamentals-1/2-c-language-fundamentals/14xc.bmp

The compiler will first increment num1 by 1 and then will assign it to num2. While in postfix form:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375526458348/-2-c-language-fundamentals-1/2-c-language-fundamentals/14xc.bmp

the compiler will first assign num1 to num2 and hen increment num1 by 1.

Assignment Operators

Assignment operators are used to assign values to variables. Common assignment operators in C# are:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375526666208/-2-c-language-fundamentals-1/2-c-language-fundamentals/fr.png

The equals (=) operator is used to assign a value to an object. Like we have seen

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375526887616/-2-c-language-fundamentals-1/2-c-language-fundamentals/14xcd.bmp

assigns the value 'false' to the isPaid variable of Boolean type. The left hand and right hand side of the equal or any other assignment operator must be compatible, otherwise the compiler will complaint about a syntax error. Sometimes casting is used for type conversion, e.g., to convert and store a value in a variable of type double to a variable of type int, we need to apply an integer cast.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375527270392/-2-c-language-fundamentals-1/2-c-language-fundamentals/14xcdj.bmp

Of coerce, when casting there is always a danger of some loss of precision; in the case above, we only got the 4 of the original 4.67. Sometimes, casting may result in strange values:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375528067553/-2-c-language-fundamentals-1/2-c-language-fundamentals/zx.bmp

Variables of type short can only task values ranging from -3768 to 32767, so the cast above can

not assign 36982 to shortValue. Hence shortValue took the last 16 bits (as a short consists of 16 bits)

of the integer 36982, which gives the value -36985 (since bit 16, which represents the value 32768 in an int, now represents -32768). If you try to cast incompatible types like:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375528411077/-2-c-language-fundamentals-1/2-c-language-fundamentals/azc.bmp

It won't get compiled and the compiler will generate a syntax error.

Relational Operators

Relational operators are used for comparison purposes in conditional statements. Common relational

operators in c# are:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375528515929/-2-c-language-fundamentals-1/2-c-language-fundamentals/123.png

Relational operators always result in a Boolean statement; either true or false. For example if we have

two variables.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375528800444/-2-c-language-fundamentals-1/2-c-language-fundamentals/azcf.bmp

Then:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375528991964/-2-c-language-fundamentals-1/2-c-language-fundamentals/azcfg.bmp

Only compatible data types can be compared. It is invalid to compare a bool with an int, so if you have

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375529206324/-2-c-language-fundamentals-1/2-c-language-fundamentals/1q.bmp

you cannot compare i and c for equality (i==c). Trying to do so will result in a syntax error.

Logical and Bitwise Operators

These operators are used for logical and bitwise calculators. Common logical and bitwise operators in C#

are:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375764299478/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/d.bmp

The operators &, | and ^ are rarely used in usual programming practice. The NOT operator is used to negate a Boolean or bitwise expression like:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375764850792/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/hgch.bmp

Logical Operators && and || are used to combine comparisons like

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375765377374/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/hf.bmp

In the first comparison: i>3 && j<10 will="" result="" in="" true="" only="" if="" both="" the="" conditions="" i="">3 and j<10 result in true.

In the second comparison: i>3 || j<10 will="" result="" in="" true="" if="" any="" of="" the="" conditions="" i="">3 and j<10 result in true. You can, of course, use both && and || in single statement like:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375765904929/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/gd.bmp

In the statement we used parenthesis to group our conditional expressions and to avoid any ambiguity.

You can use & and | operators in place of && and || but for combining conditional expressions, && and ||are more efficient because they use "short circuit evaluation". For example, if in the expression (i>3 && j<10), i="">3 evaluates to false, the second expression j<10 won't be checked and false will be returned (when using AND, if one of the participant operands is false, the whole operands will result in false). Hence, one should be very careful when using assignment expressions with && and || operators. The &and | operator don't do short circuit evaluation and do execute all the comparisons before returning the result.

Other Operators

There are some other operators present in C#. A short description of these is given below:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375786565306/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/sd.bmp

Operator Precedence

All operators are not treated equally. There is a concept of "operator precedence" in C#. For example:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375786934640/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/sdd.bmp

2 will be multiplied by 6 first then the result will be added to 3. This is because the multiplication operator*

has precedence over the addition operator + . For a complete table of operator precedence, consult MSDN or the .Net framework documentation.

Flow Control And Conditional Statements

The if...else statement

Condition checking has always been the most important construct in any language right from the time of the assembly language days. C# provides conditional statements in the form of the if..else statement. The structure of this statement is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375787850458/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/ff.bmp

The else clause above is optional. A typical example is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375788677812/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/ff1.bmp

In the above example, the console message will be printed only if the expression i==5 evaluates to true. If you would like to take some action when the condition does not evaluate to true, then you can useelse clause:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375789804153/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/ggsdf.bmp

Only the first message will be printed if i is equal to 5. In any other case (when i is not 5), the second message will be printed. If you want to use a block of statements (more than one statement) under if or else, you can enclose your block in { } brackets:

I would always recommend to use { } brackets to enclose the statement following if and else even if only have a single statement. It increases readability and prevents many bugs that otherwise can result if you neglect the scope of if and else statements.

You can also have if after else for further conditioning:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375855911621/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/1qwk.bmp

Here else if(i==6) is executed only if the first condition i==5 is false, and else at line 9 will be executed only if the second condition i==6 (line 5) executes and fails (that is, both the first and second conditions fails). The point here is else at line 9 related if on line 5.

Since if...else is also a statement, you can use it under if...else statement (nesting), like:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375857738374/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/258.bmp

The else on line 7 is clearly related to if on line 3 while else on line 13 belongs to if on line 1. Finally, do note (C/C++ programmers especially) that if statements expect only Boolean expressions and not integer values. It's an error to write:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375858173394/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/258c.bmp

Instead, you can either use:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375858599819/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/nm.bmp

Or,

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375858784582/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/nma.bmp

The keys to avoiding confusion in the use of any complex combination of if...else are:

  • Habit of using { } brackets with every if and else.
  • Indentation: aligning the code to enhance readability. If you are using Visual Studio.Net or some other editor that supports coding, the editor will do indentation for you . Otherwise, you have to take care of this yourself.

I strongly recommend you follow the above two guidelines.

The Switch...case Statement

If you need to perform a series of specific checks, switch...case is present in C# just for this . The general structure of the switch...case statement is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375871079420/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/df.bmp

It takes less time to use switch...case than using several if...else if statements.Let's look at it with an example:

using System;

// To execute the program write "SwitchCaseExample 2" or

// any other number at command line,

// if the name of .exe file is "SwitchCaseExample.exe"

namespace CsharpProgramming

{

class SwitchCaseExample

{

     //Demonstrates the use of switch...case statement along with

    // the use of command line argument

    public static void Main(string [] userInput )

    {

        int input = int.Parse(userInput [0]);

        // convert the string input to integer.

        // Will throw a run-time exception if is no input  at run-time or if

        // the input is not castable to integer. 

        switch (input) // what is input?

        {

            case 1:      // if it is 1

                Console.WriteLine("You typed 1(one) as the first command line argument");

                break;  // get out of switch block

            case 2:   // if it is 2

               Console.WriteLine("You typed 2(two) as the first command line argument");

                break;  // get out of switch block

            case 3:   // if it is 3

                Console.WriteLine("You typed 3(three) as the first command line argument");

                break; // get out of switch block

            default:  // if it is not any of the above

                Console.WriteLine("You typed a number other than 1,2 and 3");

                break; // get out of switch block

        }             

    } 

}

}

The program must be supplied with an integer command line argument. First, compile the program (at the command line or in Visual Studio.net). Suppose we made an exe with name "SwitchCaseExample.exe", we would run it at the command line like this:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375873455310/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/lj.bmp

Or:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375873595800/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/yt.bmp

If you did not enter any command line arguments or gave a non-integer argument, the program will raise an exception:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375873740497/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/hg.bmp?height=90&width=400

Let's get to internal working. First, we converted the first command line argument (userInput[0]) into an int variable input. For conversion, we used the static Parse() method of the int data type. This method take a string and returns the equivalent integer or raises an exception if it can't. Next we checked the value of input variable using a switch statement:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375874264129/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/kii.bmp

Later, on the basis of the value of input, we took specific actions under respective case statements. Once our case specific statements end, we mark it with the break statement before the start of anothercase (or the default) block.

case 3: // if it is 3

              Console.WriteLine("You typed 3(three) as first command line argument");

              break; // get out of switch block

If all the specific checks fail (input is none of 1,2 and 3), the statements under default executes.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375941261674/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/ed.bmp

There are some important points to remember when using the switch...case statement in C#:

  • You can use either integers (enumeration) or strings in a switch statement
  • The expression following case must be constant. It is illegal to use a variable after case:

Case 1: // Incorrect syntax error

  • A colon : is used after the case statement and not a semicolon ;
  • You can use multiple statements under single case and default statements:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375942599267/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/re.bmp

  • The end of the case and default statements is marked with break (or go to) statement. We don't use { } brackets to mark the block in switch...case as we usually do in C#
  • C# does not allow fall-through. So, you can't leave case or default without break statement (as you can in Java or C/C++). The compiler will detect and complain about the use of fall-through in the switch...case statement.
  • The break statement transfers the execution control out of the current block.
  • Statements under default will be executed if and only if all the case checks fail.
  • It is not necessary to place default at the end of switch...case statement. You can even place the default block before the first case or in between cases; default will work the same regardless of its position. However, Making default the last block is conventional and highly recommended. Of course, you can't have more than one default block in a single switch...case.

Loop In C#

Loop are used for iteration purposes, i.e., doing a task multiple times (usually until a termination condition is met)

The for Loop

The most common type of loop in C# is the for loop. The basic structure of a for loop is exactly the same as in Java and C/C++ and is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375943346560/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/fgb.bmp

Let's see a for loop that write the integers from 1 to 10 to the console:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375943847217/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/gf.bmp

At the start, the integer variable i is initialized with the value of 1. The statements in the for loop are executed while the condition (i<=10) remains true. The value of i is incremented (i++) by 1 each time the loop starts.

Some important points about the for loop

All three statements in for(), assignment, condition and increment/decrement are optional. You can use any combination of three and even decide not to use any one at all. This would make what is called and 'Indefinite or infinite loop' (a loop that will never end until or unless the break instruction is encountered inside the body of the loop). But, you still have to supply the appropriate semi colons:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375944337852/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/axd.bmp

If you don't use the { } brackets, the statement immediate following for() will be treated as the iteration statement. The example below is identical to the one given above:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375944958376/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/98.bmp

I will again recommend they you always use { } brackets and proper indentation.

If you declare a variable in for()'s assignment, its life (scope) will only last inside the loop and it will die after the loop body terminates (unlike some implementations of C++). Hence if you write:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376116495877/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/58.bmp

The compiler will complain at line 1 that "i is an undeclared identifier".

You can use break and continue in for loops or any other loop to change the normal execution path. break terminates the loop and transfers the execution to a point just outside the for loop:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375945417544/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/65.bmp

The loop will terminate once the value of i gets greater than 5. If some statements are present after break,break must be enclosed under some condition, otherwise the lines following break will become unreachable and the compiler will generate a warning (in Java, it's a syntax error).

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375945867102/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/21.bmp

Continue ignores the remaining part of the current iteration and starts the next iteration.

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1375946092418/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/569.bmp

Console.WriteLine will be executed for each iteration except when the value of i becomes 5. The sample output of the above code is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376115525787/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/sa.bmp

The do...while Loop

The general structure of a do..while loop is

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376115696244/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/vd.bmp

The statements under do will execute the first time and then the condition is checked. The loop will continue while the condition remains true. The program for printing the integers 1 to 10 to the console using the do...while is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376116082222/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/7.bmp

Some important points here are:

  • The statements in a do...while() loop always execute at least once.
  • There is a semicolon ; after the while statement.

while Loop

The while loop is similar to the do...while loop, except that it checks the condition before entering the first iteration (execution of code inside the body of the loop). The general from of a while loop is:

https://sites.google.com/site/wwwcsharpprogrammingcom/_/rsrc/1376116495877/-2-c-language-fundamentals-1/2-c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/c-language-fundamentals/58.bmp

C# Language Fundamentals

| Our program to print the integers 0 to 10 to the console using while will be: | | --- |