Thursday, May 13, 2010

BOXING AND UNBOXING TYPES

BOXING AND UNBOXING TYPES

Boxing refers to converting a value type to an object type, and unboxing refers to the opposite.
Boxing is carried out implicitly in C#, use type casting to unbox to an appropriate data type.

For example
int i; Console.WriteLine("i={0}",i);

The WriteLine() method requires an object, so in the above statement integer i is implicitly boxed to an object and passed to the WriteLine method.

An example for unboxing is
    int i;
    object obj = i;  // boxing is implicit
    int j;
    j = (int) obj; // to unbox we use type cast

Typically unboxing is done in a try block. If the object being unboxed is null or if the unboxing cannot succeed because the object is of a different type, an InvalidCastException is thrown.

DELEGATES
A delegate essentially creates a name for a the specific type/signature of a method. Delegates are type safe function pointers.
One must first declare a delegate.

// delegates.cs
    using System;
// declare delegate with the signature of the  encapsulated method
    delegate void MyDelegate(string m,int a,int b);
    class Application
    {
        public static void Main()
        {
             MyDelegate md = new MyDelegate(FirstMethod);
             md += new MyDelegate(SecondMethod);
            md("message A",4,5);
            md("message B",7,11);
         } // end Main
}

    static void FirstMethod(string s1,int x1,int y1)
    {
         Console.WriteLine("1st method: " + s1);
         int sum1 = x1 + y1;
         Console.WriteLine("sum1 = " + sum1);
    }
   static void SecondMethod(string s2,int x2,int y2)
   {
         Console.WriteLine("2st method: " + s2);
          int sum2 = x2 + y2;
          Console.WriteLine("sum2 = " + sum2);
    }

OUTPUT :

1st method message A
sum1 = 9
2st method message A
sum2 = 9
1st method message B
sum1 = 18
2st method message B
sum2 = 18


TYPES :

The typeof command is an operator. It resolves at compile time and operates over a type. To check whether an object is compatible to a specific type is to apply the is keyword.

// myTypeof.cs
using System;
using System.Text;
class myTypeof
{
    public static void Main()
     {
             double b = 3.14;
             string s = "xxx";
             StringBuilder sb = new StringBuilder("123456789");
    }
        Type at = typeof(double);
        Console.WriteLine("at = {0}",at);
        Type st = typeof(string);
        Console.WriteLine("st = {0}",st);
        Type sbt = typeof(StringBuilder);
        Console.WriteLine("sbt = {0}",sbt);
        if(s is string)    
         {
            
Console.WriteLine(at);
          }
          if(s is StringBuilder)    
          {
                
Console.Write("s is of the StringBuilder");
           }
            else
            {
                 Console.Write("s is not of StringBuilder");
            }
        if(b is int)
        {
        Console.WriteLine("b is int");
         }
}

Arrays


Arrays in C#


Array Declaration :
An Array is a collection of values of a similar data type. Technically, C# arrays are a reference type. Each array in C# is an object and is inherited from the System.Array class. Arrays are declared as:

[] = new [];

Let's define an array of type int to hold 10 integers.

int [] integers = new int[10];

The size of an array is fixed and must be defined before using it. However, you can use variables to define the size of the array:

int size = 10;
int [] integers = new int[size];

You can optionally do declaration and initialization in separate steps:

int [] integers;
integers = new int[10]

It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and separating individual values with a comma:

int [] integers = {1, 2, 3, 4, 5}

This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.

Accessing the values stored in an array

To access the values in an Array, we use the indexing operator [int index]. We do this by passing an int to indicate which particular index value we wish to access. It's important to note that index values in C# start from 0. So if an array contains 5 elements, the first element would be at index 0, the second at index 1 and the last (fifth) at index 4. The following lines demonstrate how to access the 3rd element of an array:

int [] intArray = {5, 10, 15, 20};
int j = intArray[2];

PROGRAM :


// demonstrates the use of arrays in C#
static void Main()
{
    // declaring and initializing an array of type integer
    int [] integers = {3, 7, 2, 14, 65};
    // iterating through the array and printing each element
    for(int i=0; i<5; i++)
    {
        Console.WriteLine(integers[i]);
    }
}

Here we used the for loop to iterate through the array and the Console.WriteLine() method to print each individual element of the array. Note how the indexing operator [] is used.

The above program is quite simple and efficient, but we had to hard-code the size of the array in the for loop. As we mentioned earlier, arrays in C# are reference type and are a sub-class of the System.Array Class. This class has lot of useful properties and methods that can be applied to any instance of an array that we define. Properties are very much like the combination of getter and setter methods in common Object Oriented languages.

Properties are context sensitive, which means that the compiler can un-ambiguously identify whether it should call the getter or setter in any given context. We will discuss properties in detail in the coming lessons. System.Array has a very useful read-only property named Length that can be used to find the length, or size, of an array programatically.

 Using the Length property, the for loop in the above program can be written as:

for(int i=0; i
{
Console.WriteLine(integers[i]);
}

This version of looping is much more flexible and can be applied to an array of any size and of any data-type. Now we can understand the usual description of Main(). Main is usually declared as:

static void Main(string [] args)

The command line arguments that we pass when executing our program are available in our programs through an array of type string identified by the args string array. 



Arrays More Explained:

An array is a data structure that contains a number of variables. These are accessed through computed indices. C# supports one-dimensional arrays, multidimensional arrays (rectangular arrays) and arrays of arrays (jagged arrays). As C, C++ and Java C# arrays are zero indexed. This means the array indexes start as zero. 

When declaring arrays, the square bracket [] must come after the type, not the identifiers, for example int[] table. 

The size of the array is not part of its type as it is in the C language. Thus

int[] numbers = new int[20];


Array Initialization :

 
int[] numbers = {0, 1, 2, 3, 5};


This is identical to the complete initialisation statement:
int[] numbers = new int[] {0, 1, 2, 3, 5}; 


In C# arrays are actually objects. System.Array is the abstract base type of all
array types. The class Array contains methods for sorting and searching. 


// myArray.cs
using System;
class myArray 

{

    public static void Main() 

    {
            int[] numbers = { 4, 12345, 890, 23456789 }; 
            int prod = numbers[2]*numbers[0]; 
            Console.Write("prod = " + prod); 
            Console.Write("\n"); 
            int numb = Array.BinarySearch(numbers,4); 
            Console.Write("numb = " + numb); 
            Console.Write("\n"); 
            double[] d = new double[3];
            d[0] = 1.1; d[1] = 3.4; d[2] = 8.9; 
            int dpos = Array.BinarySearch(d,8.9); 
            Console.Write("dpos = " + dpos);  
   }
           Console.Write("\n"); 

            string[] slist = { "otto", "uli", "carl", "marius", "jacob" };
            int pos1 = Array.BinarySearch(slist,"carl"); 

            Console.Write("pos1 = {0}",pos1); 
             Console.WriteLine();
             Array.Sort(slist); 

              // sorting the array int pos2 = Array.BinarySearch(slist,"carl");
             Console.Write("pos2 = {0}",pos2); Console.WriteLine();
             for(int j=0;j

            { 
                Console.WriteLine("{0} {1}",j,slist[j]); 
            }
}


To create multidimensional arrays the array initializer must have as many levels of nesting as there are dimensions in the array. Thus:


int[,] numbers = {{0, 2}, {4, 6}, {8, 10}, {12, 17}, {16, 18}};


The outermost nesting level corresponds to the leftmost dimension. The innermost nesting level corresponds to the rightmost dimension. The length of each dimension of the array is determined by the number of elements at the corresponding nesting level in the array initializer. Thus the example above creates a two-dimensional array with a length of five for the leftmost dimension and a length of two for the rightmost dimension. For example


int[,] numbers = new int[5,2];


and initialises the array with:


numbers[0,0] = 0; numbers[0,1] = 2;
numbers[1,0] = 4; numbers[1,1] = 6; 
numbers[2,0] = 8; numbers[2,1] = 10; 
numbers[3,0] = 12; numbers[3,1] = 14; 
numbers[4,0] = 16; numbers[4,1] = 18;


JAGGED ARRAYS :


Jagged arrays are arrays of arrays. The element arrays do not all have to be the same.


using System;
public class TwoDim 

{
         public static void Main() 

        { 
                int[][] matrix = new int[2][]; // rows 
                matrix[0] = new int[2]; // 
               columns matrix[1] = new int[2];  // columns 
               matrix[0][0] = 2; matrix[0][0] = 4; 
               matrix[1][0] = 7; matrix[1][1] = 3; 

                int i = 1; 
                Console.WriteLine("matrix[" + i + "][" + i + "] = " + matrix[i][i]);

                double[,] myarray; 

                myarray = new double[2,3]; 
                myarray[0,0] = 3.1; myarray[0,1] = 4.7; myarray[0,2] = 3.3; 
                myarray[1,0] = 2.7; myarray[1,1] = 1.1; myarray[1,2] = 7.3;
                double r = myarray[0,1]*myarray[1,2]; 
                Console.WriteLine("r = " + r); 
        } // end Main
}

Flow Of Control and Conditional Statements


Introduction
A program based purely on sequential execution will, during each execution, always perform exactly the same actions; it is unable to react in response to current conditions.

The flow of control is the order in which statements of a program are executed.Other terms used are ordering and control flow.Group of statements used for the exact purpose , collectively called branching statements.A branch is a segment of a program made up of one statement or a group of statements.

A branching statement chooses to execute just one of several statements or blocks of statements .The choice made depends on a given condition.Branching statements are also called selection statements  or alteration statements.
An iteration statement repeats a statement or a block of statements until a given termination condition is met.Iteration statements are also referred to as loop statements or repetition statements.

Branching With The IF Statement
The value of relational operators is that they can be used to make decisions to change the flow of the execution of your program. The if keyword can be used with the relational operators to change the program flow.

The if-else keyword is used to compare two values. The standard format of the if command is as follows:

if( val1 [operator] val2) statement(s) else statement(s);

operator is one of the relational operators; val1 and val2 are variables, constants, or liter- als; and statement(s) is a single statement or a block containing multiple statements. Remember that a block is one or more statements between brackets.

If the comparison of val1 to val2 is true, the statements are executed. If the comparison of val1 to val2 is false, the statements in the fast loop are executed.


EXAMPLE :

// ifelsetest.cs- The if statement
//----------------------------------------------------
 
 class ifelsetest
{
     public static void Main()
     {
         int Val1 = 1;
         int Val2 = 0;
        System.Console.WriteLine(“Getting ready to do the if...”);

        if (Val1 == Val2)
         {
            System.Console.WriteLine(“If condition was true”);
         }
        else
        {
            System.Console.WriteLine("If condition was false");
        }
         System.Console.WriteLine(“Done with the if statement”);
    }

  }

OUTPUT :
Getting ready to do the if...
Done with the if statement


THE SWITCH STATEMENT :
C# provides a much easier way to modify program flow based on multiple values stored
in a variable: the switch statement. The format of the switch statement is as follows:
switch ( value )
{
    case result_1 :
                // do stuff for result_1
                    break;
    case result_2 :
                // do stuff for result_2
                    break;
   ... case result_n :
                // do stuff for result_x
                    break;
     default:
                // do stuff for default case
                    break;

}

 The value in the switch statement can be the result of an expression, or it can be a variable. This value is then compared to each of the values in each of the case statements until a match is found. If a match is not found, the flow goes to the default case. If there is not a default case, flow goes to the first statement following the switch statement.

When a match is found, the code within the matching case statement is executed. When the flow reaches another case statement, the switch statement ends. Only one case statement is executed at most. Flow then continues, with the first command following the switch statement.


Example :

// roll.cs- Using the switch statement.
//-------------------------------------------------------------------- 
class roll
{
    public static void Main()
     {
        int roll = 0; 

// The next two lines set the roll to a random number from 1 to 6

         System.Random rnd = new System.Random();
         roll = (int) rnd.Next(1,7);

         System.Console.WriteLine(“Starting the switch... “);

         switch (roll)
         {

        case 1:
                    System.Console.WriteLine(“Roll is 1”);
                    break;
       case 2:
                    System.Console.WriteLine(“Roll is 2”);
                    break;
       case 3:
                    System.Console.WriteLine(“Roll is 3”);
                    break;
       case 4:
                    System.Console.WriteLine(“Roll is 4”);
                    break;
       case 5:
                    System.Console.WriteLine(“Roll is 5”);
                    break;
       case 6:
                    System.Console.WriteLine(“Roll is 6”);
                    break;
       default:
                    System.Console.WriteLine(“Roll is not 1 through 6”);
                    break;

        }

            System.Console.WriteLine(“The switch statement is now over!”);

     }
 
 }

OUTPUT :
Starting the switch...
Roll is 1
The switch statement is now over!

NOTE : Your answer for the roll in the output might be a number other than 1.

EXECUTING MORE THAN ONE CASE STATEMENT
:

To do this in C#,  goto command is used. The goto command can be used within the switch statement to go to either a case statement or the default command. The following code snippet shows the switch statement from the previous section executed with goto statements instead of simply dropping through:

switch (roll)
         {

        case 1:
                    goto case 4;
                    break;
       case 2:
                    goto case 5;
                    break;
       case 3:
                   goto case 4;
                    break;
       case 4:
                    System.Console.WriteLine(“Roll is Odd”);
                    break;
       case 5:
                    System.Console.WriteLine(“Roll is Even”);
                    break;
       default:
                    System.Console.WriteLine(“Roll is not 1 through 6”);
                    break;

        }

ITERATION STATEMENTS :


An Iteration statement repeats a statement or a block of statements until a given termination condition is met.
C# provides a number of iteration statements.The iteration statements in C# are listed here:

  • while
  • do
  • for
  • foreach
THE WHILE LOOP STATEMENT :

The while loop repeats a statement or  compound statement again and again, here referred as loop body, as long as its associate loop condition, consisting of a Boolean expression, is true. When the loop conditions is false while being evaluated, flow of control moves to the line immediately following the while loop.

Syntax :

while ( condition )
{
    Statement(s);
}

Example :

class WhileTest
{
    public static void Main()
    {
            int n = 1;
            while (n < 5) 
            {
                 Console.WriteLine("Current value of n is {0}", n);
                     n++;
            }
    }
}

OUTPUT :

Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4


THE DO-WHILE LOOP STATEMENT :  

The do-while loop is analogous to the while loop in that the loop body is repeatedly executed over and over again as long as 
the Boolean expression is True.One important difference is that the loop body is located between the keywords do and while is executed before the Boolean expression is evaluated. Consequently, the loop body of the do-while loop is always executed at least once, 
even if the Boolean expression is false initially.

Example :
class Do-WhileTest
{
    public static void Main()
   
 {
            int n = 1;
            do 
            {
                 Console.WriteLine("Current value of n is {0}", n);
                     n++;
            }while (n < 5)
    }
}


OUTPUT :
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4

THE FOR LOOP STATEMENT :
The three key components of a loop are as follows
  • Loop Condition - When evaluated to true, will cause the loop body to be repeated.
  • Loop Initialization - During the loop initialization the variable(s) taking part in the loop condition are assigned initial suitable values.This process only takes place once before the loop commences.
  • Loop Update - Updates the variables of the loop condition. This is repeatedly done during every loop.

Example :

class For
{
    public static void Main()
   
 {
            int n = 1;
            for(n=1;n<5;n++)
            {
                 Console.WriteLine("Current value of n is {0}", n);            }
            Console.ReadLine();    }
}


OUTPUT :
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4

THE FOREACH LOOP STATEMENT :

The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traverse items 
in a collection or an array. The foreach loop is used for traversing each items in an array or a collection of items and displayed one by one.
Example :
using System;

class Program
{
    static void Main()
    {
        // Use a string array to loop over.
        string[] ferns = { "Psilotopsida", "Equisetopsida", "Marattiopsida", "Polypodiopsida" };
        // Loop with the foreach keyword.
        foreach (string value in ferns)
        {
            Console.WriteLine(value);
        }
    }
}

OUTPUT :
Psilotopsida
Equisetopsida
Marattiopsida
Polypodiopsida

Friday, April 23, 2010

DATA TYPES IN C#


WHAT IS TYPE?

In daily usage, the word type usually signifies a number of persons or items sharing one or more particular characteristics. This often causes a group of people of the same type to be regarded as a more or less precisely defined group.In C#, all values belonging to a specific type can be used to share a set of predefined characteristics.

THE TYPES OF C#

C# is a strongly typed language.Every value in C# must have a type.There are two kinds of data types in C#.

  • Value Types(implicit data types, structs and enumeration)
  • Reference Types(objects, delegates) 

Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit data types are defined in the language core by the language vendor, while explicit data types are types that are made by using or composing implicit data types.
Implicit data types in .Net compliant languages are mapped to types in the Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in C# has its corresponding .Net type. The implicit data types in C# are:






Implicit data types are represented in language using keywords, so each of the above is a keyword in C# (Keyword are the words defined by the language and can not be used as identifiers). It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#. The last point about implicit data types is that they are value types and thus stored on the stack, while user defined types or referenced types are stored using the heap.

A stack is a data structure that store items in a first in first out (FIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. A heap consists of memory available to the program at run time. Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non-referenced data in heap during the execution of program and returns that space to Operating System.

VARIABLES
During the execution of a program, data is temporarily stored in memory. A variable is the name given to a memory location holding a particular type of data. So, each variable has associated with it a data type and a value. In C#, variables are declared as:

Ex : int i;

The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be referred to in the rest of program by the identifier 'i'. One can initialize the variable as declared  (on the fly) and can also declare/initialize multiple variables of the same type in a single statement,

Ex : int i = 2 ;

In C# (like other modern languages), the variables must be declared before being used. Also, there is the concept of "Definite Assignment" in C# which says "local variables (variables defined in a method) must be initialized before being used".

Constant Variables or Symbols 

Constants are variables whose values, once defined, can not be changed by the program. Constant variables are declared using the const keyword, like:

const double PI = 3.142;

Constant variables must be initialized as they are declared. It is a syntax error to write:

const int MARKS;

It is conventional to use capital letters when naming constant variables.

Thursday, April 22, 2010

C# Language Fundamentals


C# LANGUAGE FUNDAMENTALS

A computer program is the formatting and use of these words in an organized manner, along with a few additional words and symbols. The key parts of a C# language include the following:


  • Whitespace
  • Keywords
  • Literals
  • Identifiers
  • Comments
  • Operators
  • Separators
NOTE : The Keywords and Comments are discussed earlier.

Whitespace :

The blank spaces put into a listing are called whitespace. The basis of this term is that, on white paper, one can never see the spaces. Whitespace can consist of spaces, tabs, line feeds, and carriage returns.

The compiler almost always ignores whitespace. Because of this, one can add as many spaces, tabs, and line feeds as desired.
For example,

int radius = 4;


This is a well-formatted line with a single space between items. This line could have had additional spaces:


int         radius         =         4 ;

This line with extra spaces executes the same way as the original.
In fact, when the program is run through the C# compiler, the extra whitespace is removed.
One can also format this code across multiple lines:


int
radius
=
4
;


Although this is not very readable, it still works.
If the text is within double quotes. It is written exactly as it is presented between the quotation marks.

Literals :
Literals are straightforward hard-coded values. They are literally what they are!
Literals can be stored by any variable with a type compatible with that of literal.

Identifiers :

Identifiers are used to name classes, methods and variables.Another aspect related to identifiers is CAPITALIZATION STYLE.The capitalization styles used in C# world are :

Pascal Casing : The first letter of each word in the name is capitalized.Recommended for naming classes and methods.
Ex: MyNewBlog.

Camel Casing : Same as Pascal casing but the first word of identifier should be in lower case.Recommend for naming variables.
Ex: myNewBlog.

Separators :
Separators are used to separate various elements in C# from each other.
Ex: Braces - { }, Parentheses - (),  Semicolon - ; , comma - , Period or dot operator .

Operators :

Operators are represented by symbols.Operators act on operands.Ex : a+b;  '+' is an Operator.

Operators are classified as Binary Operators and Unary Operators.

Binary Operators : It combines two operands to produce the result.Ex : a+b
Unary Operators : They act only upon one operand.Ex : a++

TYPES OF OPERATORS
Assignment Operator :
The assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation.


Ex : sum = a + b  or x = 10.

Assignment operators may also be chained to assign the same value to multiple variables.

Ex : a = b = c = 100.

Arithmetic Operators :
C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands.


The following table lists the primary C# arithmetic operators:

OperatorDescription
-(unary)Negates the value of a variable or expression
*Multiplication
/Division
+Addition
-Subtraction
%Modulo

Multiple Operators may be used in a single expression.

Ex : z = a + b - c * d / e.

Operator Precedence :

All operators are not treated equally. There is a concept of "operator precedence" in C#.The following table outlines the C# operator precedence order from highest precedence to lowest:


PrecedenceOperators
Highest+ -  ! ~ ++x --x (T)x

* / %

+ -

<< >>

< > <= >= is as

==  !=

&

^

|

&&

||

:?
Lowest= *= /= %= += -= <<= >>= &= ^= |=

NOTE :  The assignment operators have the lowest precedence.


Numerous compound assignment operators are available in C#. The most frequently used are outlined in the following table:

OperatorDescription
x += yAdd x to y and place result in x
x -= ySubtract y from x and place result in x
x *= yMultiply x by y and place result in x
x /= yDivide x by y and place result in x
x %= yPerform Modulo on x and y and place result in x
x &= yAssign to x the result of logical AND operation on x and y
x |= yAssign to x the result of logical OR operation on x and y
x ^= yAssign to x the result of logical Exclusive OR on x and y

Increment and Decrement Operators :
++ is an Increment Operator and -- is a decrement Operator.
The usage of these operators makes them different like Prefix and Postfix notation.

Prefix Notation :B =  ++a.This means increment by 1 first then assign it to B.
Postfix Notation : B = a++.This means first assign then increment  by 1.

Comparision Operator :


In addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean (bool) true or false result depending on the result of the comparison.

These operators are binary in that they work with two operands.
Comparison operators are most frequently used in constructing program flow control. The following table lists the full set of C# comparison operators:


OperatorDescription
x == yReturns true if x is equal to y
x > yReturns true if x is greater than y
x >= yReturns true if x is greater than or equal to y
x < yReturns true if x is less than y
x <= yReturns true if x is less than or equal to y
x != yReturns true if x is not equal to y

Logical  and Bitwise Operators :

These operators are used for logical and bitwise calculations. Common logical and bitwise operators in C# are:
Operand            Description
&                       Bitwise AND
|                         Bitwise OR
^                        Bitwise XOR
!                         Bitwise NOT
&&                     Logical AND
||                        Logical OR

The operators &, | and ^ are rarely used in usual programming practice. The NOT operator is used to negate a Boolean or bitwise expression.

The Ternary Operator :

C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows:

[condition] ? [true expression] : [false expression]

Ex : Z = x > y ? x : y ;


if x is greater than y then x is returned else, y is returned.

Tuesday, April 20, 2010

Introduction to C#



Introduction to C#

C# (pronounced C-Sharp) is a powerful and flexible programming language.Like all other programming languages, it is used to create a variety applications.
C# is an Object Oriented Programming language and has at its core, many similarities to Java, C++ and VB.In fact, C# combines the power and efficiency of C++, the simple and clean OO design of Java and the language simplification of Visual Basic.

C# removes some of the complexities and pitfalls of languages such as Java and C++.C# also does not allow multiple inheritance or the use of pointers (in safe/managed code), but does provide garbage memory collection at runtime, type and memory access checking. However, contrary to JAVA, C# maintains the unique useful operations of C++ like operator overloading, enumerations, pre-processor directives, pointers (in unmanaged/un-safe code), function pointers (in the form of delegates) and promises to have template support in the next versions.

From the above discussion, objectives of C# can be summarized as :





  • Simple
  • Modern
  • Modular
  • Object-oriented
  • Powerful and flexible
  • A Language of few words

C# is simple and modern because of its extensive features like garbage collection, extensible data types and exception handling.
It is powerful and flexible because it is limited by your imagination.
It is a language of few words ,constants also called as
Keywords which serves the built-in functionality.
Keywords, also known as
reserved words, are tokens that have special meaning in a language. The Keywords of C# are listed below :


abstractevent new struct
as explicitnull switch
base externobject this
boolfalse operatorthrow
breakfinally outtrue
bytefixed overridetry
casefloat paramstypeof
catchfor privateuint
charforeach protectedulong
checkedgoto publicunchecked
classif readonlyunsafe
constimplicit refushort
continuein return using
decimal intsbyte virtual
default interfacesealed volatile
delegate internalshort void
do issizeof while
doublelock stackalloc
else longstatic
enumnamespace string

COMMENTS IN C# 

C# Coding Style is used to robust and reliable programs.Comments are the programmer's text to explain the code, are ignored by the compiler and are not included in the final executable code. C# uses syntax for comments that is similar to Java and C++. The comment ends with the end of the line. 

Block comments:

Block comments should usually be avoided. For descriptions use of the /// comments to give C# standard descriptions is recommended. Block comments can be used in the following style :


/* Line 1
* Line 2
* Line 3
*/

Alternatively oldfashioned C style single line comments, even though it is not recommended.

/* blah blah blah */



Single Line Comments:

These are used for commenting sections of code too.

//Single comment
A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.



THE PROGRAM-DEVELOPMENT LIFE CYCLE

The program-development cycle has its own steps. In the first step, you use an editor to create a file that contains your source code. In the second step, you compile the source code to create an intermediate file called either an executable file or a library file. The third step is to run the program to see whether it works as originally planned.
 

Creating The Source Code:



Source code is a series of statements or commands used to instruct the computer
to perform your desired tasks. These statements and commands are a set of key- words that have special meaning along with other text. As a whole, this text is readable and understandable.

Here is a snippet of C# source code:

System.Console.WriteLine(“
Hello, Blogger!”);

This line of source code writes
Hello Blogger!

Using An Editor :

An editor is a program that can be used to enter and save source code. A number of editors can be used with C#. Some are made specifically for C#, and others are not.Microsoft has added C# capabilities to Microsoft Visual Studio .NET, which now includes Microsoft Visual C# .NET. This is the most prominent editor available for C# programming.

If you don’t have a C# editor, don’t feel bad. Most computer systems include a program that can be used as an editor. If you’re using Microsoft Windows, you can use either Notepad or WordPad as your editor. If you’re using a Linux or UNIX system, you can use such editors as ed, ex, edit, emacs, or vi.
 



Naming Your Source Files :

The name should describe what the program does. Although you could give your source file any extension, .cs is recog- nized as the appropriate extension to use for a C# program source file.


Understanding the Execution of a C# Program


C# programs are created to run on the .NET Common Language Runtime (CLR). This means that if you create a C# executable program and try to run it on a machine that doesn’t have the CLR or a compatible runtime, the program won’t execute.With C#, we create only one executable program, and it runs on either machine.

C# compiler produces an Intermediate Language (IL) file. This IL file can be copied to any machine with a .NET CLR.The CLR or a compatible C# runtime does this final compile just as it is needed.Compiling the program is one of the first things the CLR does with an IL file. In this process, the CLR converts the code from the portable, IL code to a language (machine language) that the computer can understand and run. The CLR actually compiles only the parts of the program that are being used. This saves time. This final compile of a C# pro- gram is called Just In Time (JIT) compiling, or jitting.


Compiling C# Source code to Intermediate Language
 



C# compiler is used to create the IL file.For Microsoft .NET Framework SDK,  the csc command is used, followed by the name of the source file, to run the compiler. For example, to compile a source file called Blogger.cs, you type the following at the command line:

csc Blogger.cs

For other frameworks like  mono whose compiler is mcs can be compiled as :

mcs Blogger.cs

For graphical development environment such as Microsoft Visual C# .NET, compiling is even simpler. In most graphical environments, compile a program by selecting the Compile icon or selecting the appropriate option from the menu. After the code is compiled, selecting the Run icon or the appropriate option from the menus executes the program.



NOTE :
After a program is compiled, an IL file is generated. If you look at a list of the files in the
directory or folder in which you compiled, you should find a new file that has the same name as your source file, but with an .exe (rather than a .cs) extension. The file with the .exe extension is your compiled program (called an
assembly). This program is ready to run on the CLR. The assembly file contains all the information that the CLR needs to know to execute the program. According to .NET terminology, the code inside the assembly file is called managed code.


Completing the Development Cycle
 



A compiled IL file can be run by entering its name at the command-line prompt or just by Run in any other program. However, the program requires a .NET CLR. If the CLR is not installed,an error will be generated when you run the program. Installing the Microsoft .NET Framework allows to run the programs like all other programs. For other frameworks,something different is to be done. For example, when using the mono compiler (mcs), the program can be run by entering it after mono. For example, to run the Blogger program mentioned earlier, you would type the following at the command line:

mono Blogger.exe


Steps to Write a Simple C# Program
 


Possibly download and install the free Microsoft .NET SDK or Visual Studio.Net.After the .NET SDK is installed successfully,  follow these simple steps :


  • Choose a Text Editor and type the program in command console.
  • Save the file with the .cs extension.
  • Compile the Code
  • If compiled successfully, a file with .exe extension is created in the same folder.
  • Run the program.
  • Verify that the output matches the desired one.


Create Your First C# Program


class Blogger
{
      public static void Main()
      {
             System.Console.WriteLine(“Hello, Blogger!”);
       }
}



Output :
Hello, Blogger!