Thursday, September 30, 2010

Writing your first c sharp program:

Writing your first c sharp program:


Introduction:

In this article we will go through some of the basics steps to get familiar with most of the things in c sharp programs. This article explains the structure of the c sharp program, how to compile and execute the c# program by using the command prompt and also it introduces you how to use the visual studio IDE to execute the projects. Let's Start With a simple 'Hello World Program'.

Hello world Program:
Open any text editor like notepad in your windows O.S and start typing the following code


namespace HelloWorld
{
    public class Hello
    {
        public static void Main()
        {
            System.Console.WriteLine("Hello World");
            System.Console.ReadLine();
        }
    }
}

Follow the steps to execute the program:

1. Save the notepad file with the extension .cs. In this case for example save your file with your class name hello.cs

2. Go to start-> All Programs-> Visual Studio 2008->visual studio Tools->Visual studio command Prompt.

3. In the visual studio command prompt change the directory to the location of your saved file.

4. And by using the command csc hello.cs compile the program.

5. Enter hello.exe to execute the program. The output will be displayed in the command prompt.

The C# Program Structure:


As we have seen a sample c# program we will try to understand the structure of the program. The basic block diagram of the c# program structure is as follows:
 

From the above diagram it is can be understood that any project created in dot net environment is nothing but an assembly. Generally assemblies are of two types. One that which is an executable file and it comes with an extension .exe. The other one is used for code reusable and its extension is .dll. The dot net framework overall consists of huge number of  assemblies by using which we can develop robust applications. The hierarchy of c# program structure goes likes this. Assembly is collection of namespaces and in turn namespaces are collections of classes, structures, methods, properties, indexers, events, delegates and so on.

To understand more clearly about the structure of the c# program we will look at the above ‘Hello World’ more precisely. The system namespace is derived from the assembly System.


namespace HelloWorld
{
    public class Hello
    {
        public static void Main()
        {
            System.Console.WriteLine("Hello World");
            System.Console.ReadLine();
               |      |      |

            namespace class  method
        }
    }
}

Wednesday, September 29, 2010

Conditional Statements and Loop constructs


Conditional Statements:
            The following are the conditional statements are available for decision making:
  • If
  • Switch
If-else:
          If-else conditional construct is followed by a logical expression where data is compared and a decision is made on the basis of the result of comparison.
Syntax:
public class example:
{
if (expression)
      {
            statements;
      } else { statements };
}
Calculating Total interest based on the given conditions:

     Principle Amount     Rate of Interest
     >=10,000                20%
     >=8000&&<=9999          18%
     <8000                   16%

class IFCondition
    {
        public float princ, nyrs, rate, interest;
        public static void Main(string[] args)
        {
            IFCondition obj = new IFCondition();
            obj.res();
            Console.ReadLine();
        }
        public void res()
        {
            Console.Write("\n Enter Loan and No of Years");
            princ = Convert.ToInt32(Console.ReadLine());
            nyrs = Convert.ToInt32(Console.ReadLine());
            if (princ >= 10000)
            {
                rate = 20;
            }
            else if (princ >= 8000 && princ <= 9999)
            {
                rate = 18;
            }
            else if (princ < 8000)
            {
                rate = 16;
            }
            interest = princ * nyrs * rate / 100;
            Console.Write("Years:{0}", nyrs);
            Console.Write("Loan:{0}", princ);
            Console.Write("Rate of Interest:{0}", rate);
            Console.Write("Interest Amount:{0}", interest);
        }
    }

Switch case:
          It is used when there are multiple values for a variable.
public class example
{
switch (variable)
       {
          case ‘0’:
                 statements;
          break;
          . . . .
       }
}
Simple Switch Case Example:

    class SimpleSwithch
    {
        public static void Main(string[] args)
        {
            Calculator obj = new Calculator();
            obj.cal();
            Console.ReadLine();
        }
    }
    class Calculator
    {
        public int a, b, sum,diff,mul,div;
        public char c;
        public void cal()
        {
        menu:
            Console.Clear();
            Console.WriteLine("=======================================");
            Console.WriteLine("Menu");
            Console.WriteLine("1.Addition");
            Console.WriteLine("2.Subtraction");
            Console.WriteLine("3.Multiplication");
            Console.WriteLine("4.Division");
            Console.WriteLine("=======================================");
            Console.WriteLine("Enter Your Option");
            c = Convert.ToChar(Console.ReadLine());
            Console.WriteLine("Enter the Values of a,b");
            a = Convert.ToInt32(Console.ReadLine());
            b = Convert.ToInt32(Console.ReadLine());
            switch (c)
            {
                case '1':
                    sum = a + b;
                    Console.WriteLine("{0}", sum);
                    break;
                case '2':
                    diff = a - b;
                    Console.WriteLine("{0}", diff);
                    break;
                case '3':
                    mul = a * b;
                    Console.WriteLine("{0}", mul);
                    break;
                case '4':
                    div = a / b;
                    Console.WriteLine("{0}", div);
                    break;
                   
            }
            Console.WriteLine("Enter M for Menu or Any other key to Exit");
            c = Convert.ToChar(Console.ReadLine());
            if (c == 'M')
            {
                goto menu;
            }
        }
    }


Loop Structures:
  • For
  • While
  • Do- While

(a)  for loop:

     Syntax:

        for( initialization; termination;     increment/decrement )

    class forloop
    {
        public static void Main(string[] args)
        {
            implement obj = new implement();
            obj.forloop();
            Console.ReadLine();
        }
    }
    class implement
    {

        public void forloop()
        {
            Console.WriteLine("The Output is displayed by using Console.WriteLine()\n");
               for(int i=0; i<5; i++)
               {
                   Console.WriteLine("{0}", i);
               }

            Console.WriteLine("\nThe Output is displayed by using Console.Write()\n");
               for (int i = 0; i < 5; i++)
               {
                   Console.Write("{0}\t", i);
               }
        }

    }

while loop
     Syntax:
            while ( expression )
                   {
                     statements;
                   }

   do – while loop

      Syntax:
          do
           {
              statements;
           }
           while ( expression )
          {
              statements;
          }

Tuesday, September 28, 2010

Arrrays in Csharp

Arrays in csharp:
            Arrays provide the same functionality and they work similarly to how the arrays work in other programming languages. However, there are few things which you might keep in mind while working with arrays. This article explains about the different types of arrays, their methods and how to work with them.
Arrays in c# are not dynamic in size, they are fixed in size. Arrays are zero indexed, that is array index starts at zero and the total number of elements in an array is n-1. An array is represented by a single variable name. The individual elements are accessed using the variable name together with one or more indexes between. For example consider an instance where you need to display the list of products available at an Electronic Gadgets Store. One can use any one of the following syntax to accomplish this task.
Array Syntax:
string[ ] products;
products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
You can specific the length of the array at the time of variable declaration.
string[ ] products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
Entire Declaration at same time
string[ ] products = new string[ 3]  { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
 Or
 You can also omit the size and new operator as shown:
 string[ ] products = new string[ ] { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
string[ ] products = { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };

 Multi Dimension Arrays:
Multi Dimension Arrays are of two types Rectangular Arrays and Jagged Arrays.
Rectangular Arrays are arrays in which all the sub arrays in a particular dimension have same length. In our example we can use Multi Dimension Arrays to add some information for the products like Product ID and product code.
string[,] productattributes = new string[3,3] { { "GIFT", "Griffin iTrip FM Transmitter", "$42" }, 
{ "GDC", "Griffin DJ Cable", "$67" }, { "UPA", "USB Power Adapter", "$76" } };
 All the syntax declarations which are used for the single dimension array can be used for the multi dimension arrays.
 Similarly we can increase the dimension of the array to make it as three dimension. By using these three dimension array we categorize the products. The syntax for the three dimension array goes here.
Syntax:
string [, ,] productcateogries = new string[3, 1, 4]
{{{“Car Accessories", "GIFT", "Griffin iTrip FM Transmitter", "$42" } },
  {{“Cables & Docks", "GDC", "Griffin DJ Cable", "$67”}},
  {{“Power Accessories", "UPA", "USB Power Adapter", "$76”}}};

string [ ] products = new string [3] string [ products ];
string [ ] productattributes = new string[3, 3];  string [ attributes, products];
string [ ]productcateogires = new string[3,1,4];  string [categories, products, attributes];
                   

Jagged Arrays:     
                                    Jagged Arrays are arrays within arrays. Jagged Arrays can have sub-arrays with different lengths. One can combine ‘n’ number of arrays with same dimensions which may have same length or different length.                     
Continuing with our products example we can combine ‘productscategories’ Array and ‘customerorder’ array by using a jagged array and the syntax is as follows:
string[,] customers = new string[3, 3] { { "GIFT", "Johny", "$42" }, { "GDC", "Mike", "$45" }, { "GDC", "Robin", "$24" } };

string [ ][,]customerorder = new string[2][,]{productattributes, customers};

Retrieving information from arrays:
                       
                        We can retrieve the information from the arrays by using the indexes. One can a for loop or foreach loop to retrieve information from the arrays.

Using for loop:
For example you can access the array information by using the following syntax:
string productcategory  = Productscategories[2,0,0];
string productattributes = productattribute[1,0];
Now by using for loop we can iterate through all the elements in the array as shown below:
For Loop for one dimensional array:
for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("{0}",products[i]);
            }

For loop for two dimensional array:
  for( int i=0;i<3;i++)
            {
                for (int j = 0; j <3; j++)
                {
                    Console.WriteLine("{0}", productattributes[i, j]);
                }
                Console.WriteLine("================");
            }

For loop for three dimensional array:
for (int i = 0; i <2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        Console.WriteLine("{0}", customerorder[i][j, k]);
                    }
                    Console.WriteLine("================");
                }
            }
Instead of specifying the length of the array we can use the array.getlength() method as follows:

productattributes.GetLength (0) or productattributes (1) which returns the length of the arrays.

Using foreach loop:

To be more efficient in order to iterate through the collections, C# provides us with the foreach loop. With only one single line of code u can iterate through all the elements in the productattributes or productcateogries or customerorder. Foreach loop can be used as follows:

foreach(string s in productattributes)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in productcateogries)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in customerorder[0])
            {
                Console.WriteLine("{0}", s);
            }

Further Reading:
For all the methods and properties of the arrays you can visit the following link:
Most of the methods specified will work only for the single dimensional arrays and not for the multi-dimensional and jagged arrays.

Constructors


What is constructor?
  • Constructor is used to initialize an object (instance) of a class.
  • Constructor is a like a method without any return type.
  • Constructor has same name as class name.
  • Constructor follows the access scope (Can be private, protected, public, Internal and external).
  • Constructor can be overloaded.
Constructors generally following types :
  • Default Constructor
  • Parameterized constructor
  • Private Constructor
  • Static Constructor
  • Copy Constructor
The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.
Parameterized constructor

Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

Private Constructor

Private constructors are used to restrict the instantiation of object using 'new' operator.  A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.



Static Constructors

C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.

Copy Constructor

              If you create a new object and want to copy the values from an existing object, you use copy constructor. This constructor takes a single argument: a reference to the object to be copied.

 Consructor demo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp
{
    ///




    /// (a)Default Constructor
    /// (b)Parameterized Constructor
    /// (c)static Constructor
    /// (d)Copy Constructor
    /// (e)Private Constructor
    ///

    class Constructor
    {
        public static void Main(string[] args)
        {

            defaultconstructor obj1 = new defaultconstructor();
            obj1.member();
            int a, b;
            Console.WriteLine("Enter the values of a,b");
            a = Convert.ToInt32(Console.ReadLine());
            b = Convert.ToInt32(Console.ReadLine());
            constructor obj = new constructor(a, b);
            obj.display();
            privateconstructor obj2 = privateconstructor.createinstance();
            obj2.result();
            staticconstructor obj3 = new staticconstructor();
            obj3.display();
            copyconstructor ob1 = new copyconstructor(10, 20);
            ob1.display();
            // Here we are using copy constructor. Copy constructor is using the values already defined with ob1
            copyconstructor ob2 =new copyconstructor(ob1);
            ob2.display();
            Console.ReadLine();
          
        }

    }
    //(a) default constructor
    class defaultconstructor
    {
        int a, b;
        public defaultconstructor()
        {
            a = 5;
            b = 6;
        }
        public void member()
        {
            Console.WriteLine("Example of defaultconstructor");
            Console.WriteLine("The values of a is: {0} \n The value of b is: {1}", a, b);
            Console.WriteLine("===========================================================");
        }
    }
    //(b)parameterized constructor
    class constructor
    {
        int a, b;
        public constructor(int x, int y)
        {
            a = x;
            b = y;
        }
        public void display()
        {
            Console.WriteLine("Example of parameterizedconstructor");
            Console.WriteLine("Value of a: {0}",a);
            Console.WriteLine("Value of b: {0}",b);
            Console.WriteLine("===========================================================");
        }
    }
    //(c) private constructor
    class privateconstructor
    {
        public int a, b; public static int c, d;
        private privateconstructor(int x, int y)
        {
            this.a=x;
            this.b = y;
        }
        public static privateconstructor createinstance()
        {
            Console.WriteLine("Enter the values");
            c = Convert.ToInt32(Console.ReadLine());
            d = Convert.ToInt32(Console.ReadLine());
            return new privateconstructor(c,d);
        }
        public void result()
        {
            int z;
            z = a + b;
            Console.WriteLine("Example of privateconstructor");
            Console.WriteLine("The result is {0}", z);
            Console.WriteLine("===========================================================");
        }
    }
    //(d) static constructor
    class staticconstructor
    {
        static string carname, carmodel;
        static staticconstructor()
        {
            carname = "BMW";
            carmodel = "BMWZ8";
        }
        public void display()
        {
            Console.WriteLine("Example of static constructor");
            Console.WriteLine("The carname is {0}\n The carmodel is {1}", carname, carmodel);
            Console.WriteLine("===========================================================");
        }
    }
    //(e) copy constructor
    class copyconstructor
    {
        int a, b;

        public copyconstructor(int x, int y)
        {
            this.a = x;
            this.b = y;
        }
        public copyconstructor(copyconstructor a)
        {
            this.a = a.a;
            this.b = a.b;
        }
        public void display()
        {
            Console.WriteLine("Example of copy constructor");
            int z = a + b;
            Console.WriteLine(z);
            Console.WriteLine("===========================================================");
        }
    }

}