Introduction to C#

Author: Ronald S. Holland
Total Application Works

To contact us

HOME Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript

© 2002 - 2016 All Rights Reserved Total Application Works

    Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <title>C#: Table of Contents </title>
    <a href="">
    Table Tags </a>

Table of Contents

Objectives of this tutorial

After you have completed this tutorial, you should:

  • Understand the basic structure of a C# program.
  • Obtain a basic familiarization of what a "Namespace" is.
  • Obtain a basic understanding of what a Class is.
  • Learn what a Main method does.
  • Learn how to obtain command-line input.
  • Learn about console input/output (I/O).

Introduction to C#

The purpose of this tutorial is to introduce you to the basics of C# ("C sharp") variable types. Even if you've never programmed in a language similar to C/C++ or Java before, this tutorial should be very easy to follow and understand. It assumes that you have some basic exposure to programming (some object-oriented experience would be helpful, but is not necessary) and you have some kind of C# compiler (if you would like to run the examples). First, you should know that C# is a language designed by Microsoft. It is intended to combine the most significant parts of C/C++ along with the productivity of a 4GL, such as Visual Basic. If you do not have a C# compiler, instructions on how to obtain one will be described in the next section.

Free Compilers

If you don't have a c# compiler, you can download a free copy at Microsoft's 2010 Visual Studio Downloads Page or Microsoft's 2012 Visual Studio Downloads Page. This download may take approximately 24 hours using a 56 kbps dial-up. You may be able to download a copy in 5-10 minutes, if you have access to a T1 line at a public college or a public library, assuming a line is available. You may be able to download a copy in 15-20 minutes, if you have access to a broadband internet provider. You can follow the steps below:

  1. Download a free copy of VC++ at Microsoft's Visual Studio Downloads Page.
    • This copy is in image file format (ISO images).
    • I used this option: All - Offline Install ISO image file. With this option, you get the following:
      • Visual Basic 2010 Express Edition
      • Visual C# 2010 Express Edition
      • Visual C++ 2010 Express Edition
      • Visual Web Developer 2010 Express Edition
  2. Download a free copy of VCdControlTool. It only works with ISO images. Installation instructions:
    1. Copy VCdRom.sys to your WINDOWS\system32\drivers folder.
    2. Execute VCdControlTool.exe
    3. Click "Driver control"
    4. If the "Install Driver" button is available, click it. Navigate to theWINDOWS\system32\drivers folder, select VCdRom.sys, and click Open.
    5. Click "Start"
    6. Click OK
    7. Click "Add Drive" to add a drive to the drive list. Ensure that the drive added is not a local drive. If it is, continue to click "Add Drive" until an unused drive letter is available.
    8. Select an unused drive letter from the drive list and click "Mount".
    9. Navigate to the image file (VS2010ExpressWithSP1ENUX1504728.iso or VS2010Express1.iso), select it, and click "OK". UNC naming conventions should not be used; however, mapped network drives should be OK.
  3. Next use Windows Explorer to navigate to the Virtual drive you mounted. You will see the following folders:
    • Include
    • VBExpress
    • VCExpress
    • VCSExpress
    • VWDExpress
  4. Use the setup application in each folder to install the desired components.
  5. You are ready to start programming.
  6. You can download other compilers at:
    1. Bloodshed C++
    2. Dev-C++
Next, we present a brief description of 3GL languages in the next section.
What is a 3GL language?

A 3GL language is a procedural language, such as "C", COBOL, FORTRAN, and/or PASCAL. An example of a simple "C" program is shown in Figure 1.

#include <stdio.h>

/** ******************************************
 * The main function is the entry point 
 * that is called when the program is loaded 
 * into memory and begins program execution.
 * function main begins program execution
int main( void )
   printf( "Hello World!!\n\n" +
          "From Ronald S. Holland\n" + 
          "          at\n" + 
          "Total Application Works\n\n" + 
          "Welcome to C Programming!\n\n" );

   return 0; /* indicate that program ended successfully */

} /* end function main */ 
Figure 1: Example in "C"

In the next section, we will present a short list of 4GL languages.

What is a 4GL language?

A 4GL language is a very high productivity language, and for every 4GL line of code, approximately10-20 lines of 3GL of code are generated.. The following list includes some 4GL languages.

When we consider C#, we consider that it is intended to combine the most significant parts of C/C++ along with the productivity of a 4GL.

What is a multi-paradigm programming language?

A multi-paradigm programming language is one that supports more than one discipline. C# is a multi-paradigm programming language that supports imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. For those of you who are familiar with Java, you will notice similarities to Java, including syntax, strong web to your toolbox of languages should be fairly straightforward.

Requirements for a HelloWorld program

The requirements for our HelloWorld c# program that includes:

  1. A HelloWorld class;
  2. A main method;
  3. The ability to write a string to the screen;

As we begin the construction of our standard Hello World example, we will

  • Use our favorite text editor (e.g., Notepad) to create a new file,
  • Add the code below and save the output to the HelloWorld.cs file. In reality, you can name the file anything you like but we'll use HelloWorld.cs for the sake of simplicity). Correlating the name of the file similar to the task it performs will enable you to more easily find the file on your disk.

    /** *****************************************
     * File name: HelloWorld.cs
    using System;
    public class HelloWorld
       /** *****************************************
        * The main method is the entry point that is 
        * called when the program is loaded into 
        * memory.
       public static void Main( string[] args ) {
          Console.WriteLine( "Hello World!!\n\n" +
              "From Ronald S. Holland\n" + 
              "          at\n" + 
              "Total application Works\n\n" + 
              "Welcome to C# Programming!\n\n" );
       } // end Main method
    } // end class HelloWorld
    Figure 2: Hello World in C#

    You can compile the above program by:
    1. Going to the directory where you saved HellowWorld.cs
    2. Typing
        csc HelloWorld.cs
    3. Making sure the following are in the path
      • csc.exe
      • cscomp.dll
      • cscompui.dll

    This will compile your source code and create a file called HelloWorld.exe. When you double-click on the HelloWorld.exe file, the executable file will run and you should see the following output: Hello World!. When we look at the code in the above example we see the following:

    1. /** **** ... - start of a multiline/block comment
    2. * File name: HelloWorld.cs - comment line displaying the name of the file
    3. ... ******/ - end of the multiline/block comment
    4. using - Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive). In this case, System.
    5. Console - a class that represents the standard input, output, and error streams for console applications in the System namespace. This class cannot be inherited.
    6. WriteLine - is a Console class method that writes the specified data, followed by the current line terminator, to the standard output stream.
    7. public static void Main( string[] args ) - the Main method is where program execution begins and ends. Every C# program contains a Main method.
In the following section, we will explore c# data types.

C# Types

In the following sections, we will explore the following c# data types:

  • Value Types
    Value Types Description
    bool The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false.
    bool bBool = true;
    byte The byte keyword denotes an integral type that stores values from 0 to 255.
    byte myByte = 255;
    char The char keyword is used to declare a Unicode character.
    char char1 = 'Z';        // Character literal
    char char2 = '\x0058';   // Hexadecimal
    char char3 = (char)88;   // Cast from integral type
    char char4 = '\u0058';   // Unicode
    decimal The decimal keyword denotes a 128-bit data type. Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations.
    If you want a numeric real literal to be treated as 
         decimal, use the suffix m or M, for example:
         decimal myMoney = 300.5m;
             Without the suffix m, the number is treated as 
               a double, thus generating a compiler error.
    double The double keyword denotes a simple type that stores 64-bit floating-point values.
    double x = 3D;
    enum The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list.
    enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; 
    enum Days {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
    float The float keyword denotes a simple type that stores 32-bit floating-point values from (plus/minus) 1.5 × 10-45 to (plus/minus) 3.4 × 1038 .

    float x = 3.5F;

    If you do not use the suffix in the previous declaration, you will get a compilation error because you are attempting to store a double value into a float variable.
    int The int keyword denotes an integral type.

    int a = 123;
    long The long keyword denotes an integral type that stores values from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

    long long_x = 4294967296;
    sbyte The sbyte keyword denotes an integral type that stores values from -128 to 127.

    sbyte sByte_1 = 127;
    short The short keyword denotes an integral data type that stores valuesfrom -32,768 to 32,767.

    short x = 32767;
    struct A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.

    public struct Book {
       public decimal price;
       public string title;
       public string author;
    uint The uint keyword denotes an integral type that stores values from 0 to 4,294,967,295.

    uint myUint = 4294967290;
    ulong The ulong keyword denotes an integral type that stores values from 0 to 18,446,744,073,709,551,615

    ulong uLong = 9223372036854775808;
    ushort The ushort keyword denotes an integral data type that stores values from 0 to 65,535.

    ushort myShort = 65535;
    Figure 3: Data Types

  • Simple Types - consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String.
  • Integral Types - are well suited for those operations involving whole number calculations.

    Type Size (in bits) Range
    sbyte 8 -128 to 127
    byte 8 0 to 255
    short 16 32768 to 32767
    ushort 16 0 to 65535
    int 32 -2147483648 to 2147483647
    uint 32 0 to 4294967295
    long 64 -9223372036854775808 to 9223372036854775807
    ulong 64 0 to 18446744073709551615
    char 16 0 to 65535
    Figure 4: Integral Types

  • bool Types - have two values: true or false.
  • char Types - is a Unicode character, as defined by the Unicode Standard
  • Floating-Point Types - floating point type is either a float or double.
  • decimal Types - should be used when representing financial or money values.

    Type Size (in bits) precision Range
    float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
    double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308
    decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028
    Figure 5: Floating Point and Decimal Types
  • struct Types
  • Enumeration Types

Value Types

A variable of a certain value type always contains a value of that type. With the C# language, you are forced to initialize variables before you use them in a calculation. This eliminates problems with uninitialized variables because the compiler will tell you when you try to use them. When assigning a value, e.g., 5 to a value type a, the value 5 is actually copied to variable a.

ValueType a = 5 ; // After this operation, variable 'a' contains the value 5 
In contrast, for reference types, only the reference is copied; the actual value remains at the same memory location, but now two objects point to it (reference it). The value types of C# can be grouped as follows:
  • Simple types
  • struct types
  • Enumeration types

Simple Types

The simple types that are present in C# share some characteristics. First, they are all aliases of the NGWS system types. Second, constant expressions consisting of simple types are evaluated only at compilation time, not at runtime. Last, simple types can be initialized with literals. The simple types of C# are grouped as follows:

  • Integral types
  • bool type
  • char type (special case of integral type)
  • Floating-point types
  • decimal type

Integral Types

There are nine integral types in C#:

  • sbyte - The sbyte type represents signed 8-bit integers with values between -128 and 127.
  • byte - The byte type represents unsigned 8-bit integers with values between 0 and 255.
  • short - The short type represents signed 16-bit integers with values between -32,768 and 32,767.
  • ushort - The ushort type represents unsigned 16-bit integers with values between 0 and 65,535.
  • int - The int type represents signed 32-bit integers with values between -2,147,483,648 and 2,147,483,647.
  • uint - The uint type represents unsigned 32-bit integers with values between 0 and 4,294,967,295.
  • long - The long type represents signed 64-bit integers with values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
  • ulong -The ulong type represents unsigned 64-bit integers with values between 0 and 18,446,744,073,709,551,615.
  • char - The char type represents he char type represents a single Unicode character.

bool Type

The bool data type represents the Boolean values true and false. You can assign either true or false to a Boolean variable, or you can assign an expression that evaluates to either value: In contrast to C and C++, in C#, the value true is no longer represented by any nonzero value. There is no conversion between other integral types to bool to enforce this convention.

char Type

The char type represents a single Unicode character. A Unicode character is 16 bits in length, and it can be used to represent most of the languages in the world. You can assign a character to a char variable as follows:

char aChar = 'A';

In addition, you can assign a char variable via a hexadecimal escape sequence (prefix \x) or Unicode representation (prefix \u):

char aChar = '\x0065';
char aChar = '\u0065';

There are no implicit conversions from char to other data types available. That means treating a char variable just as another integral data type is not possible in C#—this is another area where C programmers have to change habits. However, you can perform an explicit cast:

char chSomeChar = (char)65;
int n_Int = (int)'A';

There are still the escape sequences (character literals) that there are in C. To refresh your memory, take a look at Figure 6.

Escape Sequences

Escape Sequence

Character Name


Single quotation mark


Double quotation mark










Form feed


New line


Carriage return


Horizontal tab


Vertical tab

Figure 6: Escape Sequences

Floating-Point Types

Two data types are referred to as floating-point types: float and double. They differ in range and precision:

  • float - The range is 1.5x10-45 to 3.4x1038 with a precision of 7 digits.
  • double - The range is 5.0x10-324 to 1.7x10308 with a precision of 15-16 digits.

When performing calculations with either of the floating-point types, the following values can be produced:
  • Positive and negative zero
  • Positive and negative infinity
  • Not-a-Number value (NaN)
  • The finite set of nonzero values
Another rule for calculations is that if one of the types in an expression is a floating-point type, all other types are converted to the floating-point type before the calculation is performed.

The decimal Type

The decimal type is a high-precision, 128-bit data type that is intended to be used for financial and monetary calculations. It can represent values ranging from approximately 1.0x10-28 to 7.9x1028 with 28 to 29 significant digits. It is important to note that the precision is given in digits, not decimal places. Operations are exact to a maximum of 28 decimal places.

As you can see, the precise. Therefore, no implicit conversions exist between decimal and double—in one direction you might generate an overflow; in the other you might lose precision. You have to explicitly request conversion with a cast.

>When defining a variable and assigning a value to it, use the m suffix to denote that it is a decimal value:

decimal decMyValue = 1.0m;

If you omit the m, the variable will be treated as double by the compiler before it is assigned.

struct Types

A struct type can declare constructors, constants, fields, methods, properties, indexers, operators, and nested types. Although the features I list here look like a full-blown class, the difference between struct and class in C# is that struct is a value type and class is a reference type. This is in contrast to C++, where you can define a class by using the struct keyword.<

The main idea of using struct is to create lightweight objects, such as Point, FileInfo, and so on. You conserve memory because no additional references are created as are needed for class objects. For instance, when declaring arrays containing thousands of objects, this makes quite a difference.

Figure 7 contains a simple struct named IP, which represents an IP address using four fields of type byte. I did not include methods and the like because these work just as with classes, which are described in detail in the next chapter.

using System;
struct IP {
  public byte b1,b2,b3,b4;

class Test {
   public static void Main() {

      IP myIP;
      myIP.b2 = 168;
      myIP.b3 = 1; 
      myIP.b4 = 101;

Figure 7: Defining a Simple struct

Enumeration Types

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. This allows you to declare a distinct type consisting of a set of named constants. For example, In its most simple form, it can look like this:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

Because I stuck with the defaults, the enumeration elements are of type int, and the first element has the value 0. Each successive element is increased by one. If you want to assign an explicit value for the first element, you can do so by setting it to 1:

enum MonthNames { January=1, February, March, April };

If you want to assign arbitrary values to every element—even duplicate values—this is no problem either:

enum MonthNames { January=31, February=28, March=31, April=30 };

The final choice is a data type different from int. You can assign it in a statement like this:

enum MonthNames : byte { January=31, February=28, March=31, April=30 };

The types you can use are limited to long, int, short, and byte.



    Table 2-1. The Size and Range of C# Integral Types
    Type Size (in bits) Range
    sbyte 8 -128 to 127
    byte 8 0 to 255
    short 16 -32768 to 32767
    ushort 16 0 to 65535
    int 32 -2147483648 to 2147483647
    uint 32 0 to 4294967295
    long 64 -9223372036854775808 to 9223372036854775807
    ulong 64 0 to 18446744073709551615
    char 16 0 to 65535

non-procedural language

    Examples of non-procedural languages are Query languages, report writers, interactive database programs, spreadsheets and application generators. In the following example, a command, such as LIST, might display all the records in a file on screen, separating fields with a blank space.

    Procedural             Non-Procedural
    Third-Generation       Fourth-Generation
    Language (3GL)         Language (4GL)
    use anyFile            use anyFile
    do while .not. eof()   
    ? name, balance        list name, balance

procedural language

    A programming language, also known as a "imperative language," that requires programming discipline, such as C/C++, Java, COBOL, FORTRAN, Perl and JavaScript. In these languages, programmers must develop a proper order of actions in order to solve the problem.

HOME Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript

To contact us

© 2002 - 2016 All Rights Reserved Total Application Works