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:

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:

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:

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.

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:

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.

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;

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.

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.

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.

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.

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:

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

One response to “C# Core Programming Construct (PART-1)”

Your email address will not be published. Required fields are marked *

Comment

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

× 8 = thirty two

About InfoSec

At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We provide the best certification and skills development training for IT and security professionals, as well as employee security awareness training and phishing simulations. Learn more at infosecinstitute.com.

Connect with us

Join our newsletter

File download

First Name

Last Name

Work Phone Number

Work Email Address

Job Title

Why Take This Training?

How will you fund your training?

What is your training budget?

InfoSec institute respects your privacy and will never use your personal information for anything other than to notify you of your requested course pricing. We will never sell your information to third parties. You will not be spammed.

Comments

What is Skillset?

Skillset

Practice tests & assessments.

Practice for certification success with the Skillset library of over 100,000 practice test questions. We analyze your responses and can determine when you are ready to sit for the test. Along your journey to exam readiness, we will:

1. Determine which required skills your knowledge is sufficient
2. Which required skills you need to work on
3. Recommend specific skills to practice on next
4. Track your progress towards a certification exam