Introduction

This article explores the core C# programming language constructs by presenting numerous stand-alone concepts such as data types, constants, iterations and conditional statements. This chapter describes on the various data type proposed by .NET frameworks. This chapter also investigates the various loops constructs in depth and takes a closer looks on conditional statements. By the end of this chapter, you obtain sufficientunderstanding in C# to write rudimentary programming constructs without using advanced Object-oriented features.

Data Types

Like any programming language, C# defines the data type to represent a variable. CLR provide two categories of data type Value Type and Reference Type. Both types are stored in different places of memory; a value type stores its value directly in stack and reference types store a reference to the value in a managed heap. Now a question arises.How do we distinguish whether it is value type of reference type?For example int is a value type and class object is a reference type.

In the following example int a and b create two memory slots declaring an int variable and assign it value of another int type variable, thus you have two separate int value in memory.

int a=2;
int b=a;

Whereas, in the reference type, a different picture came to light.In the following code, class test creates an object which reference type is:

test obj1,obj2;
obj1=new test();
obj2=obj1;

The important point to understand here is that test class revolves around objects only. obj1 and obj2 are variables of reference type and both point to the same location that contains this object.

Value type


Image 1.1 Value type Hierarchy


Image 1.2 Value type Subcategory Hierarchy

The value types have several type subcategories. The important point to note is that these are built into the language. The predefined type’s names all start with lowercase letters.


Image 1.3 Integer type Hierarchy


Image 1.4 Other Value type Hierarchy

Reference Type


Image 1.5 Reference type Hierarchy

Variables

Variables are special containers that hold some data at specific memory locations. Variables could be numeric, string, date, and character, Boolean, etc. Variables can be declared by the following syntax in C#:

Datatype identifier;

For example

int a;

Note: C# is a case sensitive language so ‘A’ and ‘a’ would be treated as different variables;

This statement declares an int type ‘a’ variable. The CLR compiler won’t allow you to use this variable until you initialize it with a value. You can initialize this variable using the equal (‘=’) sign as follows:

a=20; or int a=20;

You can declare and initialize multiple variables into a single statement, but all of the variables will be of the same type as;

int x,a=20,y=10;

The C# compiler requires that any variable must be initialized first before using in any operation, otherwise it flags out a warning. If any variable is left uninitialized into a class or structure then the vigilant C# compiler treat them zeroed.

In case of class object reference, they must also be initialized using a new keyword. We can assign a null value to the reference type as follows:

Myclass obj; // not initialized
Obj=null;
Obj= new Myclass(); // initialized

All the intrinsic data types support constructor which allows you to create a variable using anew keyword, which automatically sets the variable to its default value as;

  • bool type set to false;
  • Numeric set to 0;
  • Object reference set to Null;
  • Date set to 1/1/0001 12:00:00 AM;

Constants

A constant is a variable whose value can’t be changed throughout its lifetime, unlike primitive variables. By prefixing a variable with const keyword and later initialized it is designated as a constant variable.

const int i=10;

Constant variables have some special characteristics:

  • They must be initialized during declaration then they remain intact throughout the whole program life cycle.
  • Constant’s variables are always implicitly static.
  • Constants make your program easier to modify.

Conditional Statement

C# conditional statements allow you to branch your code depending on certain value of expression or condition. C# has two constructs for branching code – theif statement and the switch statement.

If/else construct

Theif statement allows you to test whether a specific condition is met or not. The syntax for declaring if statement as follows:

if (condition)
   Statement
else
   statement

For example, in the following program, we want to see whether the string you are working with is longer than zero character or not:

staticvoid Main(string[] args)
{
string str = "welcome home";
if (str.Length > 0)
Console.WriteLine("length is > 0");
else
Console.WriteLine("length is < 0");
Console.ReadKey();
}

You can also use an if statement without final else statement:

int data=10;
if (data !=5)
 {
Console.WriteLine("value is not equal");
 }

Note: It is not required to use curly braces on only one if statement.

If more than one statement is to be executed as part of either condition, these statements will need to be joined together into a block using curly braces ({…}) as follows:

bool isFalse;
int data;

if (data == 0)
 {
 isFalse = true;
Console.WriteLine("data is 0");
 }
else
{
 isFalse = false;
Console.WriteLine("data is not 0");
}

You can also combine the elseif statement to test multiple conditions. For example, we are checking the highest number of three as follows:

int x=10, y=20,z=22;
if (x >y)
 {
Console.WriteLine("x is Highest");
 }
elseif (x > z)
 {
Console.WriteLine("x is Highest");
 }
elseif (y > z)
 {
Console.WriteLine("y is Highest");
 }
else
 {
Console.WriteLine("z is Highest");
 }

Note: the expression in the if clause must evaluate to a Boolean (true / false)

Switch construct

The switch statement allows you to handle program flow based on predefined sets of conditions. It takes a switch arguments followed by a series of case clause. The syntax of switch construct as follows:

switch(argument)
{
 case 1:
 // Do anything
 break;
 case 2:
 // Do anything
 break;
 default:
 // Do anything
 break;
}

When the expression in the switch argument is evaluated, the code immediately following the case clause executes and you mark the end of statements by the break clause. If the expression evaluates to none of the other clauses, then you can include default clause.

Note: the order of case doesn’t matters; you can put the default case first.

The following example performs some short math operations like addition, multiply, etc. you can ask to the user at run time in form of choices what operation he want to do. Then we read two numeric values from the console and execute the operation as selected earlier.

Staticvoid Main(string[] args)
 {
int x,y;
Console.WriteLine("Enter two Integers");
 x = int.Parse(Console.ReadLine());
 y = int.Parse(Console.ReadLine());
Console.WriteLine("Operationsn-----------------------------------n");
Console.WriteLine("1= Additionn2= Subtraction n3= Multiplication");
Console.WriteLine("Operationsn-----------------------------------n");
Console.Write("Enter the operation code::");
int op = int.Parse(Console.ReadLine());
switch (op)
 {
case 1:
Console.WriteLine("Add=" + (x + y));
break;
case 2:
Console.WriteLine("Subs=" + (x - y));
break;
case 3:
Console.WriteLine("Multiply=" + (x * y));
break;
default:
Console.WriteLine("wrong choice");
break;
 }
Console.ReadKey();
 }

If all the case clauses are executed in a sequence, but you want to fire a particular case clause early, then you can do this by the goto case clause as follows:

switch (country)
 {
case"india":
gotocase"Canada";
case"USA":
break;
case"Canada":
break;
 }

Loops

Loops are essential encounters in C# which allow you to execute a block of code repeatedly until a certain condition is met. C# caters the following four constructs as;

  • for loop
  • foreach loop
  • while loop
  • do/while loop

The for loop construct

The for loop used in case of iterating a block of code to fixed number of time where you can test a particular condition before you perform another iteration. The for loop construct syntax is as follows:

for (initializer; condition; iterator)
{
 Statements;
}

Here the initializer is evaluated before the first loop is executed. The loop is executed until condition expressions are false and the iterator is responsible for incrementing of decrementing the loop counter.

The following program typically writes the value 0 to 4 on the screen by using the for loop construct. We are declaring a local variable x and initialize it to 0 which is used as loop counter. Then we test whether it is less than 5 or not in the condition block and finally you increase the counter by one and walk through the process again as follows:

int x;
for (x = 0; x < 5; x++)
 {
Console.WriteLine(x);
 }

Note that we can declare the local counter variable in the for loop block, also, and x++ can be simply written as x=x+1. You can create complex condition, endless loops and make use of goto,break and continue statements in the for loop. The program will terminate in between if the counter variable is reached to 8 as follows:

for (int i = 0; i < 10; i++)
 {
if (i == 8)
 {
break;
 }
Console.WriteLine(i);
 }

In some circumstances you want your loops to be executed infinitely.ThenC# allows you to write infinite loops by using the following syntax as follows:

for (; ;) { }

for (; ;)
 {
Console.WriteLine("printing");
 }

The for loop can be nested.That means we implement an inner for loop into outer loop. The inner loop executes once completely for each iteration of an outer loop. The following code displays prime numbers till 100 by using nested for loop.

staticvoid Main(string[] args)
 {
int i, j;
bool isPrime = false;

for (i = 2; i <= 100; i++)
 {
for (j = 2; j < i; j++)
 {
if (i % j == 0)
 {
 isPrime = true;
break;
 }
 }
if (isPrime == false)
Console.Write("{0} ", j);
else
 isPrime = false;
 }
Console.ReadKey();
 }

The foreach loop construct

The foreach loop construct allow you to iterate through each item into a collection without the need to test the upper limit condition. This construct can also be applied on user-defined collections. In the following, you can traverse an array of string as;

string[] country = { "India", "USA", "Canada", "China" };
foreach (string x in country)
 {
Console.WriteLine(x);
 }

Here, foreach loop steps through the array an element at a time. With each element, it places the value of the element in the string x variable and then performs an iteration of the loop.

The while loop construct

The while loop is mostly used to repeat a statement or a block of statements for a number of times that is not known before the loop begins. The syntax for while loop as follows:

while(condition)

Statement;

The while loop performs the expression evaluation first, then executes its body statements. A statement inside the loop body will set a Boolean flag to false on certain iteration till the end of the loop as follows:

bool status= false;
while (!status)
 {
 }

The following program checks whether the value of int x is less than 10 using while loop and display them.

int x = 0;
while (x<10)
 {
Console.WriteLine("value of x is"+ x);
 x++;
 }

The do/while loop constructs

The do/while is almost similar to its previous construct, the while loop.But ithas slight differences like the condition that is evaluated after the body of the loop has been executed. This loop is useful for the situation in which statements must execute at least once. The syntax for the do/while loop as follows:

do

{

//body

} while(condition);

The following program depicted has the same objective as in while loop but it executed the body statements first and later it checks the condition.

int</span> x = 0;
do
 {
Console.WriteLine("value of x is" + x);
 x++;
 } while</span> (x < 10);

Jump Statement

C# caters special statements that allow you to jump immediately to another line in the program. The break, continue and goto statements are known as jump statements.

The break statement

The break statements mainly used to exit the current iteration containing in for, foreach, while and do.while loops. The following example shows the break statements to exit a nested for loops as following.

for (int i = 0; i < 10; i++)
 {
Console.Write(" "</span> + i);
if (i == 5) break;
 }

Here the for loops stops its execution when the value of i is reached to 5 using the break statement. The output of this program isas follows:


Image 1.6 Break statements Output

The continue statement

The continue statements is to break statements and must also be used in for, foreach, while and do.while loops. It stop the current execution and begin or restart a new iteration, it does not exit from the current iteration as like break statement.

for (int j = 0; j < 10; j++)
 {
if (j == 5) continue;
Console.Write(" "+j);
 }

The above program does not stop the its execution when the j value reached to 5 instead it restarts the loop and continue printing the rest of output as follows:


Image 1.7 Continue Statement output

The goto statement

The goto statement allows you to jump directly to another specific line in the program indicated by a label identifier. This statement is quite handy jumping between cases in a switch statement. The following program declares a label identifier lableX to display the incremented value of x each time jumped from the condition as follows:

Want to learn more?? The InfoSec Institute Web Application Penetration Testing Boot Camp focuses on preparing you for the real world of Web App Pen Testing through extensive lab exercises, thought provoking lectures led by an expert instructor. We review of the entire body of knowledge as it pertains to web application pen testing through a high-energy seminar approach.

The Web Application Penetration Testing course from InfoSec Institute is a totally hands-on learning experience. From the first day to the last day, you will learn the ins and outs of Web App Pen Testing by attending thought provoking lectures led by an expert instructor. Every lecture is directly followed up by a comprehensive lab exercise (we also set up and provide lab workstations so you don't waste valuable class time installing tools and apps). Benefits to you are:

  • Get CWAPT Certified
  • Learn the Secrets of Web App Pen Testing in a totally hands-on classroom environment
  • Learn how to exploit and defend real-world web apps: not just silly sample code
  • Complete the 83 Step "Web App Pen Test Methodology", and bring a copy back to work with you
  • Learn how perform OWASP Top 10 Assessments: for PCI DSS compliance
int i = 0;
lableX: Console.WriteLine("label construct"+ i++);

if (i < 5)
goto lableX;