C# Core Programming Constructs

Article Overview

  • Introduction
  • Data Types
  • Variables
  • Constants
  • Conditional Statement
  • Loops
  • Jump Statement

Introduction

This article explores the core C# programming language construct by presenting numerous stand-alone concepts, such as data types, constants, iterations and conditional statements. It describes the various data types provided by the .NET Framework. This article also investigates the various loop constructs in depth and takes a closer looks at conditional statements. By the end of this article you will have a sufficient understanding of C# enough to write rudimentary programming constructs without using advanced object-oriented features.

Data Types

Like any programming language C# uses data types to represent a variable. The CLR provides the two categories of data types, Value Type and Reference Type. Both types are stored in different types of memory; a value type stores its value in the stack and a reference type stores a reference to the value in the managed heap. Now the question becomes, how to determine whether a type it is a value type or a reference type. For example int is a value type and a class object is a reference type.

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

  1. int a=2;  
  2. int b=a; 

Whereas, in the reference type a different picture exists. In the following code, the class test is used in the creation of an object that is a reference type:

  1. test obj1,obj2;  
  2. obj1=new test();  
  3. obj2=obj1; 

The important point to understand here is that a test class revolves around objects only. obj1 and obj2 are variables of a 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 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 can either be numeric, string, date, character, Boolean and so on. A variable can be declared with the following syntax in C#:

  1. Datatype identifier; 

For example:

  1. 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 in the following:

  1. 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 in the following:

  1. int x,a=20,y=10; 

The C# compiler requires that a variable must be initialized first before use in an operation, otherwise it is flagged as a warning. If a variable is left uninitialized in a class or structure then the vigilant C# compiler sets them to zero(s).

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

  1. Myclass obj; // not initialized  
  2. Obj=null;  
  3. Obj= new Myclass(); // initialized 

All the intrinsic data types support a constructor that allows creation of a variable using the new keyword that automatically sets the variable to its default value as in the following:

  • 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 the const keyword and later initializing it, it is designated as a constant variable.

const int i=10;

A constant variable has the following special characteristics:

  • They must be initialized during declaration and then they remain intact throughout the entire program's life.
  • Constant 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 a certain value of an expression or condition. C# has two constructs for branching code, the if statement and the switch statement.

If/else construct


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

  1. if (condition)  
  2. Statement  
  3. else  
  4. statement 

For example in the following program we want to determine whether or not a string is longer than zero characters:

  1. static void Main(string[] args)  
  2. {  
  3.   
  4.    string str = "welcome home";  
  5.   
  6.    if (str.Length > 0)  
  7.       Console.WriteLine("lenght is > 0");    
  8.    else  
  9.       Console.WriteLine("lenght is < 0");    
  10.   
  11.    Console.ReadKey();  
  12.  } 

You can also use an if statement without the final else statement as in the following:

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

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 then these statements will need to be joined together into a block using curly braces ({…}) as in the following:

  1. bool isFalse;  
  2. int data;  
  3.               
  4.  if (data == 0)  
  5.  {  
  6.    isFalse = true;  
  7.    Console.WriteLine("data is 0");  
  8.  }  
  9. else  
  10. {  
  11.    isFalse = false;  
  12.    Console.WriteLine("data is not 0");  

You can also combine an if/else statement to test multiple conditions. For example we are checking the highest number from the three numbers as in the following:

  1. int x=10, y=20,z=22;  
  2. if (x >y)  
  3.    {  
  4.      Console.WriteLine("x is Highest");  
  5.    }  
  6. else if (x > z)  
  7.    {  
  8.      Console.WriteLine("x is Highest");  
  9.    }  
  10. else if (y > z)  
  11.    {  
  12.      Console.WriteLine("y is Highest");  
  13.    }  
  14. else  
  15.    {  
  16.      Console.WriteLine("z is Highest");  
  17.    } 

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 argument followed by a series of case clauses. The syntax of the switch construct is as in the following:

  1. switch(argument)  
  2. {  
  3.      case 1:  
  4.      // Do anything  
  5.      break;  
  6.      case 2:  
  7.      // Do anything  
  8.      break;  
  9.      default:  
  10.      // Do anything  
  11.      break;  
  12. }  

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 clause then you can include a default clause.

Note: The order of case doesn't matter; you can put the default case first.

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

  1. Static void Main(string[] args)  
  2.         {  
  3.             int x,y;  
  4.             Console.WriteLine("Enter two Integers");  
  5.             x = int.Parse(Console.ReadLine());  
  6.             y = int.Parse(Console.ReadLine());  
  7.             Console.WriteLine("Operations\n-----------------------------------\n");  
  8.             Console.WriteLine("1= Addition\n2= Substraction \n3= Multification");  
  9.             Console.WriteLine("Operations\n-----------------------------------\n");  
  10.             Console.Write("Enter the operation code::");  
  11.             int op = int.Parse(Console.ReadLine());  
  12.   
  13.             switch (op)  
  14.             {  
  15.                 case 1:  
  16.                     Console.WriteLine("Add=" + (x + y));  
  17.                     break;  
  18.                 case 2:  
  19.                     Console.WriteLine("Subs=" + (x - y));  
  20.                     break;  
  21.                 case 3:  
  22.                     Console.WriteLine("Multiply=" + (x * y));  
  23.                     break;  
  24.                 default:  
  25.                     Console.WriteLine("wrong choice");  
  26.                     break;  
  27.             }  
  28.             Console.ReadKey();  
  29.         } 

Although all the case clauses are executed in a sequence, if you want to fire a specific case clause early then you can do this by the goto case clause as in the following:

  1. switch (country)  
  2.    {  
  3.       case "india":  
  4.       goto case "Canada";  
  5.       case "USA":  
  6.       break;  
  7.       case "Canada":  
  8.       break;  
  9.    } 

Loops

Loops in C# essentially allow you to execute a block of code repeatedly until a certain condition is met. C# provides the following four constructs:

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

The for loop construct

The for loop is for iterating a block of code a fixed number of times where you can test a specific condition before you do another iteration. The for loop construct syntax is as in the following:

  1. for (initializer; condition; iterator)  
  2. {  
  3.     Statements;  

Here the initializer is evaluated first before the first loop is executed. The loop is executed until the condition expressions are false and the iterator is responsible for incrementing or 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 initializing it to 0 to use it as loop counter. Then we test whether or not it is less than 5 in the condition block and finally you increase the counter by one and walk through the process again as in the following:

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

Note 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 a complex condition, endless loops and use goto, break and continue statements in the for loop. The following program will terminate when the counter variable 8 is reached as in the following:

  1. for (int i = 0; i < 10; i++)  
  2.     {  
  3.        if (i == 8)  
  4.          {  
  5.             break;  
  6.          }  
  7.          Console.WriteLine(i);  
  8.      } 

In some circumstance you want your loops to be executed indefinitely. C# allows you to write infinite loops using the following syntax:

  1. for (; ;) {  }  
  2.   
  3. for (; ;)  
  4.  {  
  5.  Console.WriteLine("printing");  

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

  1. static void Main(string[] args)  
  2.         {  
  3.             int i, j;  
  4.             bool isPrime = false;  
  5.   
  6.             for (i = 2; i <= 100; i++)    
  7.             {  
  8.                 for (j = 2; j < i; j++)  
  9.                 {  
  10.                     if (i % j == 0)  
  11.                     {  
  12.                         isPrime = true;  
  13.                         break;  
  14.                     }  
  15.                 }  
  16.                 if (isPrime == false)  
  17.                     Console.Write("{0} ", j);  
  18.                 else  
  19.                     isPrime = false;  
  20.             }  
  21.   
  22.             Console.ReadKey();  
  23.         } 

The foreach loop construct

The foreach loop construct allows you to iterate through each item into a collection without the necessiry of testing the upper limit condition. This construct can also be applied on user-defined collections. In the following you can traverse an array of string:

  1. string[] country = { "India""USA""Canada""China" };  
  2. foreach (string x in country)  
  3.   {  
  4.     Console.WriteLine(x);  
  5.   } 

Here, the foreach loop steps through the array element one 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 of the while loop is as in the following:

  1. while(condition)  
  2.     Statement; 

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

  1. bool status= false;  
  2. while (!status)  
  3.     {  
  4.                   
  5.     } 

The following program checks whether the value of int x is less than 10 using a while loop and displays them:

  1. int x = 0;  
  2. while (x<10)  
  3.    {  
  4.       Console.WriteLine("value of x is"+ x);    
  5.       x++;  
  6.    } 

The do/while loop constructs

The do/while is nearly similar to its previous construct while loop but has the slight difference that the condition is evaluated after the body of the loop has been executed. This loop is useful for the situation in which the statements must execute at least once. The syntax for the do/while loop is as in the following:

  1. do  
  2. {  
  3.   //body  
  4. while(condition); 

The following program depicts the same objective as in a while loop but it executes the body statements first and later it checks the condition as in the following:

  1. int x = 0;  
  2. do  
  3.   {  
  4.    Console.WriteLine("value of x is" + x);  
  5.    x++;  
  6.   } while (x < 10); 

Jump Statement

C# provides 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 are mainly used to exit the current iteration containing for, foreach, while and do..while loops. The following example shows the break statements to exit a nested for loop as in the following.

  1. for (int i = 0; i < 10; i++)  
  2.     {  
  3.       Console.Write(" " + i);  
  4.       if (i == 5) break;  
  5.     } 

Here the for loops stops its execution when the value of i reaches 5 using the break statement. The output of this program is as in the following:



Image 1.6 Break statements Output

The continue statement

The continue statement is a break statement and must also be used in for, foreach, while and do..while loops. It stops the current execution and begins or restarts a new iteration, it does not exit from the current iteration as does the break statement.

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

The preceding program does not stop the execution when the j value reaches 5, instead it restarts the loop and continues printing the rest of the output as in the following:



Image 1.7 Continue Statement output

The goto statement

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

  1. int i = 0;  
  2. lableX: Console.WriteLine("lable construct"+ i++);  
  3.   
  4. if (i < 5)  
  5. goto lableX; 

Summary

It is necessary to be familiar with the basic concepts before encountering any programming language. This article has provided an insight into the essentials of C# programming constructs like data type, loops, methods, delegates and many more. We have differentiated value types and reference types in detail in the context of C# programming. After exploring this article, the reader will be able to start moderate level of coding in C# programming.


Similar Articles