My Adsense

Thursday, November 5, 2009

Introduction to C# : A hands on approach (Part 2)

Introduction to C#: Day 2

           
            In this lesson you will be familiar with different types of C# syntax some conceptual things.
            Objectives:
            After completing this unit you should have a clear concept on:
*        Data types
*        Expressions
*        Conditional statements
*        Iteration statements
*        Methods in C#
*        Enum

You will be able to create applications using the following controls:
*        ComboBox
*        GridVeiw
*        ListView etc.


Topics

In this lesson you will learn about the following topics
*        Data types
*        Data types conversions
*        Data type: String
*        Data type: Constant
*        Expressions
*        Operators
*        Conditional statements
*        Switch
*        Iteration statements
*        Enum








Data types:
When we instruct a machine to execute some operation, the machine changes the high level language (which we are sending) into machine code (sequence of 1s and 0s).
The instruction we are sending also contains data on which the operation will be executed.
But not all data should contain the same amount of memory nor do the same types of operation. So, different sets of data have different size and perform different types of operation. And they are not interpreted in the same way.
So, a instructor (programmer) has to tell the system before-hand, the type of number or characters he is using in the instruction. These type are called Data Types. There are many data types in C# language. A programmer has to use appropriate data types as per his requirement.

There are 2 types of Data Type. They are
                                                                                 i.            Predefined Data Types
                                                                               ii.            User defined Data Types

Predefined Data Types:
This kind of data types are created by the C# creator programmers (Microsoft Programmers). They define the characteristics of the data types and also define the set of allowed activities a specific data type can do. Different types of predefined data types allocated different amount of memory and performs different types of operation.
The following data table lists the predefined data types and describes the data that they are designed to store.
Type Name
Definition
Byte
Byte
Integer (0 to 255)
1
Sbyte
Integer(-127 to 128)
1
Short
Integer (-32768 to 32767)
2
Ushort
Integer (0 to 65535)
2
Int
Integer (-2147483648 to -2147483648)
4
Uint
Integer (0 to 4294967295)
4
Long
Integer (-9223372036854775808 to -9223372036854775808)
8
Ulong
Integer (0 to 18446744073709551615)
8
Bool
Boolean value(true or false)
1
Float
Single-precision floating point value
4
Double
Double-precision floating point value
8
Decimal
Precise decimal value to 28 significant digits
12
Object
Base type of all other types
N/A
Char
Single Unicode character
2
String
An unlimited sequence of Unicode characters
N/A
                       
                        User defined data types:
User defined data types are composed of different combination of predefined data types. Sometimes a user defined data type contains another user defined data type in it. A user defined data type can also perform some operations and the definition of the operation will be stated into the type definition.

                        Working with data types:
To use a data in our program, we have to follow some specified way and use some specific keywords that are defined by the language creators.

a.       Declaration:
Declaration is something like allocating a memory space for a specific data and gives the memory address a name by which the programmer can operate on that data later. It is linking of a memory location to a data. The name of the memory location is called Variable.
Example: int count;
b.      Initialization:
Initialization is the next step of declaring of a variable. In initialization, valid data is inserted into the variable memory location. Valid data means the allowed types of data that the memory location can contain.
Example: int count = 10;
c.       Literals:
Literals are a single character used at the end of a data. It is used to put data into a memory location that is normally invalid for that memory location.
Example: decimal priceWithVat = 123.123M;

Walkthrough 1: Working with data types
            To make the data type clear, we will practice some works on data types.
            Steps:
1.      Create a new console application
2.      Declare a variable of Integer type
3.      Initialize it with some data
4.      Display the variable in the console.
5.      Now declare a float type variable and initialize it
6.      Build it
7.      You will find an error saying “Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type”
8.      Put a character ‘F’ or ‘f’ at the end of the data of the initialization statement.
float variable = 12.2f;
9.      Build it
10.  Run it


                        Data Type: String
As stated above, a string variable contains a sequence of alphanumeric characters. We can declare a string variable like other types of variable.
Example:
               string name;    // Declaration
               string firstName = "Foyzul";    //Initialization

Escape characters:
Escape characters are used when we want to set a run time meaning of a part of a string.
Example:
string greetings = "Hello everyone.\nWelcome to BASIS.";

                                    Verbatim characters:
A verbatim string is a string that is interpreted by the compiler exactly as it is written, which means that even if the string spans multiple lines or includes escape characters, these are not interpreted by the compiler and they are included with the output. The only exception is the quotation mark character, which must be escaped so that the compiler can recognize where the string ends.
Example:
string address = @"C:\Software\Books\Beginning”;
As you can see, verbatim is indicated with an ‘@’ sign at the beginning of a string.
If you want to use a quotation mark inside a verbatim string, you must escape it by using another set of quotation marks.
Example:
string greetings = @"""Hello everyone"".said the trainer.";

Walkthrough 2: Working with String types
Steps:
1.      Create a console application
2.      Declare a string variable and initialize it by your name
3.      Display the variable in console
4.      Build the solution and run it
5.      Now change the value of the variable using "Hello everyone.\nWelcome to BASIS."
6.      Build it and run it
7.      Change the value of the string with the address of your project directory using verbatim




                        Data Type: Constants
A constant is a variable whose value remains constant. Constants are useful in situations where the value that you are using has meaning and is a fixed number, such as pi, the radius of the earth, or a tax rate.
Example:
const int radiusOfEarth = 6378;                              
As you can see, constant variable starts with the keyword ‘const’ at the declaration, or initialization.
Walkthrough 3: Working with Constant
            Steps:
1.       Create a console application
2.       Declare a constant integer type variable and initialize it
3.       Display the variable in console
4.       Build it and run the application

          Data Type Conversions:
Sometimes we have to change the data that we are using. Sometimes this change may change the value of the data or sometimes it just changes the memory space allocated by that data. This change is called data type conversion.
Data type is converted in 2 ways. They are:
a.       Implicit conversion
b.       Explicit conversion
They are described below.

Implicit conversion:
An implicit conversion converts data automatically without losing any data. Normally, data types can implicitly converted into the data types those contain more memory space.
Example:
short firstNumber = 65;
long secondNumber = firstNumber;
                        Explicit conversion:
An explicit conversion convert data that are automatically can’t be converted. It may converts data from bigger size to smaller size or converts data from one type into totally different type.
Example:
short firstNumber = 65; //Initialization
 long secondNumber = firstNumber; //Implicit conversion
short thirdNumber = (short)secondNumber; //Explicit  conversion
                Console.WriteLine(thirdNumber); //outputs 65
char a = (char)firstNumber; //Explicit conversion
Console.WriteLine(a); //outputs A

We can use some built in functions those are provided with C#.
a.       Convert class:
A convert class contains numerous method those can change one data type into another type. It is another implementation of explicit conversion.
Example:
 int number = 65;    //Initialization
char character = Convert.ToChar(number);    //Conversion using System's Class
Console.WriteLine(character);   //Output: A           
b.      ToString() method:
A ToString() method converts any kind of data type into String type. It doesn’t change the internal value of that data.
Example:
char character = Convert.ToChar(65);    //Conversion using System's Class
string numberString = (65).ToString();
Console.WriteLine(character);   //Output: A
Console.WriteLine(numberString);    //Output(value is in String form): 65
                                         
Figure: A Memory location
          Walkthrough 4: Working with data conversion
          To make the conversion more clear, we will go through a walkthrough now.        
            Steps:
1.       Create a desktop application
2.       Design a user interface given below




3.       Select the last textbox and change its Readonly property to True
4.       Double click on the button
5.       Write down the following code into the button click event block
 int firstNumber = Convert.ToInt32(firstNumberTextBox.Text);
                        int secondNumber = Convert.ToInt32(secondNumberTextBox.Text);
                        int sum = firstNumber + secondNumber;
sumTextBox.Text = sum.ToString();
6.       Build the application and run it


          Expressions:
An expression is a sequence of operators and operands. An operator is a concise symbol that indicates the action that you want to occur in your expression.
An operand is the value on which an operation is performed.
An operator is specifically designed to produce a new value from the value that is being operated on.
Example:
Conditional operator: &&,||
Mathematical operator: +

            Conditional statements:
A conditional statement allows you to control the flow of your application by selecting the statement that is executed, based on the value of a Boolean expression.
                        Syntax:
a.       If(boolean-expression)         statement
b.       If(boolean-expression) statement1
else statement2
c.       If(boolean-expression) statement1
else if(boolean-expression) statement2
else statement3
                        Example:
                        bool condition;
if (condition == true)
            {
                Console.WriteLine("condition is true");
                                            }
            else
                if (condition == false)
                                                                {
                    Console.WriteLine("condition is false");
                }
                else
                                                                {
                    Console.WriteLine("unknown valueA+");
                                                                }
d.       If((boolean-expression) operator (boolean-expression)) statement
Example:
if (scoreOutOfHundred >= 60 && scoreOutOfHundred < 80)
                                {
                          return "A+";
 }
e.       (boolean-expression) ? (statement1) : (statement2)
Example:
         bool value = true;
 Console.WriteLine(value ? "True Value" : "False Value");
           
          Walkthrough 5: Working with conditional statements      
            Steps:
1.       Create a desktop application
2.       Design the user interface like the following figure



3.       Double click on the button
4.       Write down the code snippet in the block
                         string planetName=planetNameComboBox.Text;
                         if(planetName=="Planet")
                         {
                                 MessageBox.Show("It is in 3rd position");
                         }
                         if(planetName=="Saturn")
                        {
                                 MessageBox.Show("It is in 6th position");
                        }
                        if(planetName=="Mars")
                        {
                                 MessageBox.Show("It is in 4th position");
                         }
5.       Build the solution and run it

          Iteration Statements:
C# provides several looping mechanisms, which enable you to execute a block of code repeatedly until a certain condition is met. In each case, a statement is executed until a Boolean expression returns true. By using these looping mechanisms, you can avoid typing the same line of code over and over.
a.       For loop:
A for loop must have 3 basic parameters. It must have a loop initializer value, a loop ending value and also an increment/decrement operator. These 3 types of value can be written in any part of the for loop block. But generally, these are written in the heading part of the loop.
Example:
         for (int count = 0; count < endingValue; count++)
                                                {
                    sum += count;
                }
b.      While loop:
While loop first checks a boolean expression and then enters into the code block. This loop runs until that expression turns into false.
Example:
         while (condition == true)
                                                {
                    sum += count++; ;
                                     if (count > 50)
                                                                {
                        condition = false;
                                                }
                                                }
c.       Do-While loop:
Do while loop first executes the whole code block one time and then checks the boolean expression. If the expression is false, this loop quit execution and go to the next statements. Otherwise, it runs until it finds the boolean expression false.
Example:
                       do
                                       {
                sum += count++;
}while (count < 10);

                        Keywords:
                                    Continue:
To continue the loop operation without executing the rest of the statements on the block, continue keyword is used.
                                    Break:
                                                Break keyword is used to break the loop.
                                    Example:
for (int count = 0; count < MAXIMUM_VALUE; count++)
                      {
                    if (count == expectedValue)
                {                    
                              break;
                                                                                  }
                else
                          {
                        continue;
           }
                                                       }


          Walkthrough 6: Working with iteration statements
          Steps:
1.       Create a desktop application
2.       Design the user interface like the following figure



3.       Double click on the button and write the code snippet given below
int itemNumber = Convert.ToInt32(numberTextBox.Text);
                        for (int count = 1; count <= itemNumber; count++)
                       {
                          numberListView.Items.Add(count.ToString());
                       }
4.     Build the solution and run it

[Note: I assumed all of my readers are Computer Science Graduate so that I haven’t made the theoritical parts more lengthy.]

No comments: