General C# Programming Constructs

In this post we will look at a few commonly used constructs in C#.

1.   Declaring Variables in C#

Variables in C# are declared in the following way:

AccessModifier DataType VariableName;

The access modifier could be public, protected, private or internal. As you know access modifiers define the level of access that certain blocks of code has to class members like its methods and properties. This access level for each modifier is described below:

Access Modifier Description
public Makes a member accessible from anywhere.
protected Makes a member accessible within the class and all classes derived from it only.
private Makes a member accessible only within a class.

As far as the internal modifier is concerned we shall be discussing it in a later post.

The DataType could be any of the valid variable types in C#. A few of the valid intrinsic C# data types are listed below:

C# Data Type Description
int Declares a variable which stores Integer values. Takes up 4 bytes of memory.
string Declares a variable which stores string values.
float Declares a variable which stores integer values with decimals.

 The data type could also be an array definition or a custom data type like enumerators or maybe even a class name for creating an object. We shall discuss all of these in later posts.

Then follows the variable name, which should be a valid C# variable name. The rules for naming variables in C# are just the same as in C.

In almost all programming languages, keywords are not allowed to be used as identifiers. However, C# has a work-around for this issue. You can use variables which clash with keywords by prefixing the identifier with an @ symbol. The @ is not considered as a part of the identifier however.

Consider the Example 2.

Example 2:

using System;
class Test
{
   static void Main()
   {
      int @int;
      @int = 5;
      Console.WriteLine(@int);
   }
}

Note that in Example 2 we have declared a variable of the type int, and the variable name is also int. We have just pre-fixed the variable name with an @ symbol.

Another new feature related to variables in C# is that they are automatically assigned a default value upon creation. Consider the following example 3.

Example 3:

using System;
class Test
{
   static void Main()
   {
      int[] MyArr = new int[3];
      Console.WriteLine(100 * MyArr[1]);
   }
}

The output of the program will be:

0

In Example 3 we have declared an array of integers called MyArr and no values have been assigned to the array elements. Yet the program does not generate an error when we use the unassigned array element (in the last statement). The compilation and execution takes place smoothly. The reason is that C# assigns a default value to the array elements that are declared. The default value for the type int is zero. This is why the output of above example is 0 (as 100 * 0= 0).

Below Table lists out the default values of common data types.

Type Default Value
Numeric (int, float, short, …) 0
Bool False
Char ‘’
Enum 0
Reference null

 However, remember, this type of default assignment on unassigned elements occurs only for static fields, class instance fields and array elements. For all other variables, the compiler will throw an error. Hence it is considered a good programming practice to assign a value to a variable before using it.

2.   Basic Input Output in C#

Basic input and output operations are performed in C# using the methods of the Console class in the System namespace.

The two widely used methods are

  • WriteLine()
  • ReadLine()

We have already used Console.WriteLine in previous posts. However Console.WriteLine is even more powerful. It can be used to format text before displaying it. It takes up to four additional parameters, which are known as the format string specifiers. The format string specifiers specify how data will be displayed. It can also serve as placeholders, which determine where the values of the specified variables will be displayed in the string.

Consider Example 4, which is a slight variant of Example 3.

Example 4:

using System;
class TestDefaultValues
{
   static void Main()
   {
      int number, result;
      number = 5;
      result = 100 * number;
      Console.WriteLine(“Result is {0} when 100 is multiplied by number”, result);
   }
}

“{0}” acts as a placeholder, which determines where the value of the specified variable (result) will be displayed.

The output of Example 4 will be:

Result is 500 when 100 is multiplied by number

To get input from the user, Console.ReadLine is used. The ReadLine() method reads all characters up to a carriage return. The input is returned as string.

Consider Example 5.

Example 5:

using System;
class InputString
{
   static void Main()
   {
      string input;
      input = Console.ReadLine();
      Console.WriteLine(“{0}”, input);
   }
}

The program will accept a line from the user and echo it back as the output.

3.   Selection Statements in C#

The selection statements are used to perform operations based on the value of an expression. Checking for conditions in C# is the same as in C. We use the if construct for performing conditional branching. The syntax for the if construct is as follows:

if (expression)
{
   // Statements if expression evaluates to True
}
else
{
   // Statements if expression evaluates to False
}

As you can see it is very similar to the C constructs. However, one major difference is that in C# the expression should always evaluate to an expression of Boolean type. This can be understood better with the help of the following example.

Example 6:

int number = 1;
if (number)
   System.Console.WriteLine(“The value is True”);
if (number == 1)
   System.Console.WriteLine(“The value is True”);

When the first if statement is encountered by the compiler it will generate the following error:

Error CS0029: Cannot implicitly convert type ‘int’ to ‘bool’

The error pops up as the expression “number” will not evaluate to a boolean value. While the second if statement will work just fine, as the expression will either result in a True or False. This is a major difference among other programming languages and shows the power of C#’s type safety features!

Next is the switch statement. The switch statement is very similar to the one we used in C, except that in C# it is mandatory to specify a break statement for each and every case block, without which the compiler will generate an error.

The syntax for a switch construct is as follows:

switch (variable)
{
   case value:
      // Statements
   case value:
      // Statements
   default:
      // Statements
}

The switch construct can be used in place of multiple if statements. Example 7 illustrates an example of how a switch statement can be used.

Example 7:

switch (Choice)
{
   case 1:
      Console.WriteLine(“You Choose One”);
      break;
   case 2:
      Console.WriteLine(“You Choose Two”);
      break;
   default:
      Console.WriteLine(“This is the Default Option”);
      break;
}

As it is clear from Example 7, the break statement after each case is not optional as in C/C++. It needs to be specified if the program is to be compiled. No fall troughs are allowed.

One more enhancement in the switch statement in C# over the switch statement of C/C++ is that it allows the switch construct to be used along with strings.

4.   Iteration Constructs in C#

Iteration or looping statements are used to perform a certain set of instructions a certain number of times or while a specific condition is true.

C# provides us with the following types of iteration constructs,

  • The while loop
  • The do loop
  • The for loop
  • The foreach loop

Except for the foreach loop all others are very similar to the ones in C. We shall look at each and every one of them in detail.

  • The while loop

The while loop iterates through the specified statements till the condition specified is true. However, unlike the while loop in C, the C# while loop requires a boolean condition just like the C# if construct.

The syntax for a C# while loop is as shown below:

while (condition)
{
   // Statements
}

The break statement can be specified in the statements to break out of the loop at any time. The continue statement can be specified to skip the current iteration and begin with the next iteration.

  • The do loop

A do loop is very similar to a while loop except that in a while loop the condition is first evaluated and then the execution takes place, whereas, in a do loop the condition is evaluated at the end of the loop. In a do loop the statements in the body of the loop get executed at least once before the condition is checked.

The syntax for a C# do loop is as follows

do
{
   // Statements
} while (condition)

The break and continue keywords can be used even in the do loop.

  • The for loop

The for loop, as in C, is a little different from the other loops. The loop variables maybe declared as part of the for statement.

The syntax for a for loop in C# is as given below:

for (initialization; condition; increment/decrement)
{
   // Statements
}
  • The foreach loop

The foreach loop is new to the C/C++ programmer but instantly familiar to the Visual Basic programmer as the concept has been borrowed into C# from Visual Basic. The foreach loop is usually used to iterate through a collection or an array.

The syntax for a foreach construct is as follows:

foreach (Type Identifier in expression)
{
   // Statements
}

Consider Example 8:

Example 8:

using System;
public class ForEachEx
{
   static void Main(String[] args)
   {
      foreach(String str in args)
      {
         Console.WriteLine(str);
      }
   }
}

If we compile and run the program by passing the three names as the command line parameters as shown below:

ForEachEx Scooby Scrappy Shaggy

The output will be:

Scooby

Scrappy

Shaggy

The foreach loop simply iterates through the array args and puts the values contained within it one at a time into the variable str, which is then displayed on the console.

5.   Constructors in C#

As we already know, constructors are special methods. As in case of C++, the constructor in C# also has the same name as the class. Example 9 below provides the syntax for defining a constructor for a class.

Example 9:

…
class MyClass
{
   public MyClass()
   {
      // MyClass Constructor
   }
}
…

6.   Destructors in C#

Destructors in C# are written in the same way as constructors are written. The destructors in C# have the same name as the class except that there is a ~ (tilde) symbol prefixed to it.

Building on Example 9 is Example 10,

Example 10:

…
class MyClass
{
   public MyClass()
   {
      // MyClass Constructor
   }

   public ~MyClass()
   {
      // MyClass Destructor
   }
}
…

The destructors in C#, though, are defined just as in C++; they tend to behave differently as the destructor is called by the Garbage Collector. The Garbage Collector is a service of the .net runtime, the CLR. The exact working of the Garbage Collector will be discussed at a later post.

Leave a comment