Learn C# By Example

This blog will take various topics of C# programming and provide easy examples for understanding the concepts.

Saturday, December 30, 2006

Looping Statements:

Overview :

for statement

The for statement is used for iterating over a set of statements multiple times using an expression. The expression is evaluated after each run of the iteration and stops when the expression evaluates to false.

Let us see an example:

Type this code using your favourite editor:

Compile and run the program:

While Statement

do staement

do while statement

Conditional Statements and Looping

Most of the programming languages provide for conditional constructs, to enable the developer to provide for decision making in the program and respond to multiple scenarios.

The IF Statement:

Assuming you are writing a program, which:

1) Asks the user his age

2) If the age is > 30 the program outputs "You are so old"

3) If the age is < 30 the program outputs "You are so young"

Type this program in your favourite text editor:

Compile the program using the csc compiler . The syntax is : csc SampleIfStatement.cs

To Run the program, call the program with one paramter as the age:

The IF Statement with ELSE IF:

There are situationns wherein you may want to handle more than 1 situations in your code. Normally if there
were too many possibilities , you would go for the SWITCH statement which will take it later on. But if there

are just 2/4 possibilities , you may use the IF statement with the ELSE IF flavour.

Let us take an example to get a more clear idea for this construct:

Type this code in your favourite editor:

Compile and run the program:

Switch Case Statement

The Switch statement can be used to control the flow of the program by passing control to one of the case statements which evaluates to true in the scenario.

For example you want to write a program which does the following:

1) Take the input of the user

2) If the user enters 1 : output "You selected Option 1: Add User"

3) If the user enters 2: output "You selected Option 2: Delete User"

4) If the user enters 3: output "You selected Option 3: Modif User"

5) If the user enters any other number : output "You selected to Exit"

Edit the Program for Switch Case Statement:

Compile and run the program:

File Handling Using C#

The .NET Framework provides a extensive collection of base classes in the .NET Framework which make most of the work of file handling an efficient task, with the developer needed to write only the calls to these classes.

To use the file handling classes efficiently , you may want to review the classes and their methods under the package System.IO. We will cover some of the important classes, in our use-and-study methodology through the code samples itself.

Let us see in action how the file handling is done using .NET file handling classes:

Reading a Text File

To read a text file , we will use the class StreamReader which provides an implementation of the Abstract class, TextReader and hence supports the following methods :

  • Read() -- Reads data from an input stream.
  • ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.

    ReadToEnd() -- Reads all characters to the end of the TextReader and returns them as one string

    Let us write a class which reads a text file and outputs its contents to the system console.

    Please type the following code using your favourite text editor:

    Compile the program using the C# Compiler:

    Run the Program:

    Before you run the program , create a flat file with the name "samplefile.txt" and put any text in it and save

    it in the same directory as the program.

    Now you are ready to run the program, which will read this file and output the text to the system console:

    Writing a Text File

    We will use the class StreamWriter to write to a file. When we write to a file there are multiple possibilities, that the file may or may not exist, if the file is existing, we may have to specify whether the program should append to the existing file or overwrite the file.

    The StreamWriter has the following constructors :

    StreamWriter(System.String) Constructor
    This constructor takes one paramter as String, which needs to be a valid filename.

    StreamWriter(System.String, bool) Constructor
    This constructor takes an additional parameter which is bool, this paramter is the flag for overwriting the file if it exists.

    StreamWriter(System.IO.Stream) Constructor
    StreamWriter(System.IO.Stream, System.Text.Encoding) Constructor
    StreamWriter(System.IO.Stream, System.Text.Encoding, int) Constructor
    StreamWriter(System.String, bool, System.Text.Encoding) Constructor
    StreamWriter(System.String, bool, System.Text.Encoding, int) Constructor

    StreamWriter Methods

    StreamWriter.Write(System.String) Method

    This method takes a string to write to the file.

    StreamWriter.WriteLine(System.String) Method

    This method is inherited from the TextWriter class,this method takes a string and writes to the file with a newline character.


    StreamWriter.Write(char[], int, int) Method
    StreamWriter.Write(char[]) Method
    StreamWriter.Write(char) Method

    StreamWriter.Close Method
    StreamWriter.Dispose Method
    StreamWriter.Finalize Method
    StreamWriter.Flush Method

    Let us now create a program which creates a new text file and writes to it:

    Type in the following program using your favourite text editor:

    Compile the program:

    Run the program to do a dir on the directory to see if a new file is created:

  • As you will see a new file has been created and our text has been printed to that file.

    Executable C# Class:

    Every C# class, which needs to be run as an executable needs to have the following method:

    public static void Main()

    {

    }

    or

    public static void Main(String[] args)

    {

    }

    When you run the compiled exe, the code in the

    method is called first.

    Since we wanted to create an exe, our code also contains this code, which is

    called when the exe is executed.

    The next line we need to understand is :

    Console.WriteLine("Hello World! How are you");

    The WriteLine method in the System.Console class, lets you specify a string, which

    is printed on the system console.

    The Console class is part of the System package in the Core .NET classes.

    Classes:

    The class is a foundation of an Object orieneted programming paradigm. You can use a class to encapsulate the complexity of physical implmentation from other programming units. Anybody can get the benefits of this implementation as long as they know the constructors, the destructors and the methods.

    The Constructor:

    A constructor is a method with the same name as the class. A blank constructor is automatically called when the object of the class is created. One of the key difference between a normal method and a constructor is that , the constructor does not return any value.

    Methods :

    A method is a wrapper for a sectional piece of code in a class, which does implments a part of the functionality of the class itself. For example, if you have a class called Calculator, there may be methods like addNumber(), substractNumber()

    Method Parameter:

    Methods can be defined with parameters, every parameter is defined with its datatype. For example addNumber (int firstNumber, int secondNumber)

    Method return values:

    Methods are required to define a return data type, or if it is intended to not return type, then the method should be defined as returning void. For example : public void resetNumbers()

    As with any other programming languages, let us start with a simple program called a "hello world". This program will just display a line "Hello World" , but in the process, we plan to learn:

    1) How to write a basic C# progam

    2) Sections of a c# program

    2) How to compile a basic c# program

    using System;

    public class HelloWorld

    {

    static void Main(string[] args)

    {

    Console.WriteLine("Hello World! How are you");

    }

    }

    Typing /Editing your first program:

    Open your favourite text editor, which can be "notepad" or "editplus" or any other text editor

    you prefer and type out the above program.

    Save the program as "HelloWorld.cs"

    Compiling your first program:

    Open the visual studio command prompt

    Type the C# Compiler by calling : csc

    Pass the C# Compiler the name of your program : in this case HelloWorld.cs

    Press enter.

    If you have not made any syntax errors, the program will compile and you should see

    the following in the command window

    Your first program will be compiled into an exe file, run a dir command if there is an exe file in the directory:

    As you see, the directory contains an exe file : HelloWorld.exe

    Run the exe file by typing : HelloWorld.exe and press enter

    There you are !!!. Your first C# program has run successfully and you see the output "Hello World" in the console.