Application security

C# Core Programming Construct (PART-1)

Ajay Yadav
April 1, 2013 by
Ajay Yadav

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.

11 courses, 8+ hours of training

11 courses, 8+ hours of training

Learn cybersecurity from Ted Harrington, the #1 best-selling author of "Hackable: How to Do Application Security Right."

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.

[csharp]

int a=2;

int b=a;

[/csharp]

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

[csharp]

test obj1,obj2;

obj1=new test();

obj2=obj1;

[/csharp]

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

[csharp]

int a;

[/csharp]

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:

[csharp]

Myclass obj; // not initialized

Obj=null;

Obj= new Myclass(); // initialized

[/csharp]

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:

[csharp]

if (condition)

Statement

else

statement

[/csharp]

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

[csharp]

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();

}

[/csharp]

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

[csharp]

int data=10;

if (data !=5)

{

Console.WriteLine("value is not equal");

}

[/csharp]

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:

[csharp]

bool isFalse;

int data;

if (data == 0)

{

isFalse = true;

Console.WriteLine("data is 0");

}

else

{

isFalse = false;

Console.WriteLine("data is not 0");

}

[/csharp]

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

[csharp]

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");

}

[/csharp]

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:

[csharp]

switch(argument)

{

case 1:

// Do anything

break;

case 2:

// Do anything

break;

default:

// Do anything

break;

}

[/csharp]

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.

[csharp]

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();

}

[/csharp]

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:

[csharp]

switch (country)

{

case"india":

gotocase"Canada";

case"USA":

break;

case"Canada":

break;

}

[/csharp]

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:

[csharp]

for (initializer; condition; iterator)

{

Statements;

}

[/csharp]

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:

[csharp]

int x;

for (x = 0; x < 5; x++)

{

Console.WriteLine(x);

}

[/csharp]

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:

[csharp]

for (int i = 0; i < 10; i++)

{

if (i == 8)

{

break;

}

Console.WriteLine(i);

}

[/csharp]

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:

[csharp]
for (; ;) { }

for (; ;)

{

Console.WriteLine("printing");

}

[/csharp]

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.

[csharp]

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();

}

[/csharp]

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;

[csharp]

string[] country = { "India", "USA", "Canada", "China" };

foreach (string x in country)

{

Console.WriteLine(x);

}

[/csharp]

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:

[csharp]

bool status= false;

while (!status)

{

}

[/csharp]

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

[csharp]

int x = 0;

while (x<10)

{

Console.WriteLine("value of x is"+ x);

x++;

}

[/csharp]

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.

[csharp]

int</span> x = 0;

do

{

Console.WriteLine("value of x is" + x);

x++;

} while</span> (x < 10);

[/csharp]

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.

[csharp]

for (int i = 0; i < 10; i++)

{

Console.Write(" "</span> + i);

if (i == 5) break;

}

[/csharp]

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.

[csharp]

for (int j = 0; j < 10; j++)

{

if (j == 5) continue;

Console.Write(" "+j);

}

[/csharp]

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:

[csharp]

int i = 0;

lableX: Console.WriteLine("label construct"+ i++);

if (i < 5)

goto lableX;

[/csharp]

Ajay Yadav
Ajay Yadav

Ajay Yadav is an author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with abundant premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming and Exploit Development.

He is a regular contributor to programming journal and assistance developer community with blogs, research articles, tutorials, training material and books on sophisticated technology. His spare time activity includes tourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com