http://www.developer.com/

Back to article

The C# Data Types and Programming Constructs


September 19, 2002

In this article, we will examine the fundamentals of the C# language, which include the following:

  • Data Types and Variables
  • Programming Constructs

Data Types and Variables

Data Types are an integral part in any programming language. They represent how to express numbers, characters, strings, decimal point values, and so forth. To illustrate, if you want to express 25 in C#, you can write a code as shown below:

Listing 1

int x = 25

In the above code, int represents the integer data type. x denotes a variable name. Variables are nothing but a storage area in the memory. 25 is the value for the variable x. Without a variable you cannot store values. Keep in mind that int is an alias for the data type Integer. It has a fixed limit beyond which the data type will not hold values. Like Integer, all data types have aliases and a fixed range of values.

You should use a data type best suited to your programming needs. For example, if you are writing code for developing a calculator, it's better to use data types, which will accept large values. This will avoid runtime program errors.

Let's look at another scenario. The data type Byte accepts values only up to 255. If you try to apply a value of 300 for the corresponding variable, there will be errors during program execution. These errors are called Exceptions; they will be discussed in another article. If you had applied the data type Integer for the above program, this problem would have been avoided. Please go through Table 1 for a detailed list of all data types.

Table 1     List of Data Types
.NET Class Related DataType .NET Class Related DataType
System.Byte byte System.Sbyte sbyte
System.Int16 short System.Int32 int
System.Int64 long System.UInt16 ushort
System.UInt32 uint System.UInt64 ulong
System.Single float System.Double double
System.Object object System.Char char
System.String string System.Decimal decimal
System.Boolean boolean    

Basically, data types in C# are classified into two types: value-based and reference-based. Let's examine each of these types in detail.

Value-Based Data Types include all numerical data types such as Integer, Float, Byte, and so forth. Here you are working directly with values. When you try to assign one value type to another, a bit wise copy is achieved as shown in Listing 2:

Listing 2

using System;
struct Valdata
{
  public int a;
  public int b;
}

class Valtype
{
  public static void Main(string[] args)
  {
    Valdata v = new Valdata();
    v.a = 200;
    v.b = 300;
    Valdata v1 = v;
    Console.WriteLine(v.a);
    Console.WriteLine(v.b);
    Console.WriteLine(v1.a);
    Console.WriteLine(v1.b);

    Console.WriteLine("##################################");
    v1.a = 800;
    Console.WriteLine(v1.a);
    Console.WriteLine(v.a);
  }
}

Note that even if you change the values of one variable, the value of another variable won't change.

Reference types include Classes and Interfaces. Here, if you change the value of one variable, the value of the other variable also reflects the same value. Also, after creating an object of a class, you are working directly on that object and not with the actual values as in value types. Hence, copies of reference types results in a shallow copy. To illustrate, change the definition of the above type from a C# structure to a C# class (in the above code) and observe the result.

Boxing and Unboxing

The conversion of a value type into a reference type is termed as boxing; the conversion of a reference type into a value type is termed as unboxing. Verify the code in Listing 3:

Listing 3

// Value type
int X = 100;

// x boxed to a object type which is reference based,
// no explicit cast required
object Y = X; 

// y unboxed to an integer type, explicit cast required
// while unboxing
int Z = (int)Y

Programming Constructs

In this session, we will discuss the commonly used programming constructs like if-else, Switch-case, for, while, and do-while loops. Let's analyze each of them in detail.

If - Else

This is one of the popular decision-making statements, which is similar to that of its C++ and Java counterparts. Its usage is given below.

Usage

if(Condition)
{
  Statements
}
else
{
  Statements
}

If the condition satisfies, the statements inside the if block will be executed; otherwise, statements inside the else part will execute as shown in Listing 4:

Listing 4

using System;
class Fund
{
  public static void Main()
  {
    int x1 = 50;
    int x2 = 100;
    if(x1>x2)
    {
      Console.WriteLine("X1 is greater");
    {
    else
    {
      Console.WriteLine("X2 is greater") 
    }
  }
}

Switch - Case

This is also one of the decision-making statements which is regarded as an alternative to if - else. Its usage is given below.

Usage

switch(expression)
{
  case 10: Number is 10;break
  case 20: Number is 20;break
  case else: Illegal Entry;break
}

When the expression matches with a case value, the corresponding statements would be printed. Listing 5 explains the usage of Switch - Case statement.

Listing 5

using System;
class Switchexample
{
  public static void Main()
  {
    int wday = 2;
    switch(wday)
    {
      case 1: Console.WriteLine("Monday");break;
      case 2: Console.WriteLine("Tuesday");break;
    }
  }
}

Looping Statements

For loop

This loop is used to iterate a value fixed number of times. Its usage is given below:

Usage

for(Initial Value, Condition, Incrementation / Decrementation)
{
  Statements
}

You have to specify Incrementation and Decrementation using ++ and - operators. Listing 6 examines the working of the for loop. Here, numbers from 1 to 10 will be printed as output. 10 will also be printed because we have used <= operator. Try using only the +< operator and observe the result.

Listing 6

using System;
class Forexample
{
  public static void Main()
  {
    for(int I = 1; I<=10;I++)
    {
      Console.WriteLine(I);
    }
  }
}

While loop

This loop is similar to the for loop, except that condition is specified first and is used to repeat a statement as long as a particular condition is true. The usage of while loop is given below:

while(Condition)
{
  Statements
}

If the condition is false, statements within the loop will not be executed. Listing 7 examines the working of while loop:

Listing 7

using System;
class Whileexample
{
  public static void Main()
  {
    int I = 1;
    while(I <=10)
    {
      console.WriteLine(I);
    }
  }
}

Do - While

This looping statement is also similar to that of the previous one but the condition is specified last. Its usage is given below:

Usage

do
{
  Statements
}while(Condition)

In this case, the condition is tested at the end of the loop. Hence, the statements within the loop are executed at least once, even if the condition is false. Let's verify an example:

Listing 8

using System;
class Whileexample
{
  public static void Main()
  {
    do
    {
      int I = 1; 
    } while(I<=10);

    Console.WriteLine(I);
  }
}

Foreach

If you had used Visual Basic, you would be familiar with the foreach statement. C# also supports this statement. Listing 9 illustrates the usage of this statement:

Listing 9

using System;
using System.Collections;
class Foreachdemo   
{
  public ArrayList numbers;

  Foreachdemo() {
  numbers = new ArrayList();
  numbers.Add("One");
  numbers.Add("Two");
  numbers.Add("Three");
  numbers.Add("Four");
  numbers.Add("Five");
}

public static void Main() 
{
  Foreachdemo fed = new Foreachdemo();

  foreach(string num in fed.numbers) 
  {
    Console.WriteLine("{0}",num);
  }
}

In the above example, an object of type ArrayList is created and values are added to it using the Add method of the ArrayList class. Try removing the second using directive and observe the result.

Break statement

This statement is used to terminate a loop abruptly. We have seen the usage of this statement while discussing decision-making statements. Listing 10 examines the working of this statement.

Listing 10

using System;
class Whileexample
{
  public static void Main()
  {
    for(int I = 1; I<=10; I++)
    {
      Console.WriteLine(I);
      if(I==5)
      {
        break;
      }
    }
  }
}

About the Author

Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials. He can be reached at anand@learnxpress.com.

# # #

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date