Friday, September 21, 2012

Constructors

Constructors : 
 
Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  • Constructors and destructors do not have return types nor can they return values.
  • References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword virtual.
  • Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
 
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.

Constructors are classified into two types in c#.
They are

 1. Instance Constructors
 2.Non Instance Constructors

 Instance Constructors :

In Instance constructors. again we have 4 types of constructors.they are
1.Default Constructor
2.Parametrized
3.Copy Constructor
4.Private Constructor.

Noninstance Constructor :

We have only one constructor. ie Static Constructor


 

Thursday, September 13, 2012

Wednesday, September 12, 2012

Encapsulation and Inheritance

Encapsulation
Encapsulation is a process of binding the data members and member functions into a single unit.
Example 
A class can contain data fields and methods.
Consider the following class
public class Aperture
{
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}
 
In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier.



Inheritance:

Inheritance is a process of deriving the new class from already existing class.
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. 

There are 5 types of inheritances in C#. they are

1.Single Inheritance
2.Multilevel INheritance
3.Multiple Inheritance
4.Hybrid Inheritance
5.Hierarchical inheritance.


Single Inheritance :

when a single derived class is created from a single base class then the inheritance is called as single inheritance.

Different types of inheritance 
 
Program :
 
using System;
namespace ProgramCall

{
   class BaseClass

    {
      //Method to find sum of give  2 numbers

        public int FindSum(int x, int y)

        {

          return (x + y);

        }

        //method to print given 2 numbers

        //When declared protected , can be accessed only from inside the derived class

        //cannot access  with the instance of  derived class

        protected void Print(int x, int y)

        {

            Console.WriteLine("First Number: " + x);

            Console.WriteLine("Second Number: " + y);

         }

    }


    class Derivedclass : BaseClass

    {

      public void Print3numbers(int x, int y, int z)

        {

            Print(x, y); //We can directly call baseclass members

            Console.WriteLine("Third Number: " + z);

        }


    }

     class MainClass

    {

      static void Main(string[] args)

        {

            //Create instance for derived class, so that base class members
            // can also  be accessed

            //This is possible because  derivedclass is inheriting base class

             Derivedclass instance = new Derivedclass();

            instance.Print3numbers(30, 40, 50); //Derived class internally calls base class method.

            int sum = instance.FindSum(30, 40); //calling base class method with derived class instance

            Console.WriteLine("Sum : " + sum);

            Console.Read();

        }

    }

}

Output

First Number: 30
Second Number: 40
Third Number: 50
Sum : 70

OOPS Part -1

What is OOP?

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts. 

In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. 

What is a Class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations. 

Ex :
public class Employee
{
}
  
Creating object :
 
Employee obj=new Employee(); 
 

According to the sample given above ,we can say that the student object, named objectStudent
has created out of the Student class.
 
In the software world, though you may not have realized it, you have already used classes. 
For example, the TextBox control, you always used, is made out of the TextBox class, 
which defines its appearance and capabilities. Each time you drag a TextBox control, 
you are actually creating a new instance of the TextBox class. 
 

Object : 

It is a real time entity.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior.
 In pure OOP terms an object is an instance of a class.
Class is composed of three things name, attributes, and operations .

OOPS Features : 

If any programming language wants to be a object oriented programming language. then it needs to satisfy class and objects. then it needs to satisfy following four features. they are

1.Encapsulation
2.Inheritance
3.Polymorphism
4.Data abstraction.

C#  is strong object oriented programming language.

Access Modifiers in c# :

Access Modifier Description (who can access)
private Only members within the same type. (default for type members)
protected Only derived types or members of the same type.
internal Only code within the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types)
protected internal Either code from derived type or code in the same assembly. Combination of protected OR internal.
public Any code. No inheritance, external type, or external assembly restrictions.

Accessibility :
 
Public - any item in the current assembly or any assembly that references the class, can access this member.
Protected - access is limited to the containing class or types derived from the containing class.
Internal - any item in the current assembly can access this member.
Protected internal - access is limited to the current assembly or types derived from the containing class.
Private - access is limited to the containing class. 


Class Members in c# : 

In C#, a class have following members,.
1.Data fields
2.Methods
3.Constructors
4.Destructors
5.Properties
6.Events
7.indexers.

Fields - instances of objects that are considered part of a class, normally holding class data.
 

Properties - methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the object's knowledge. For a more detailed understanding see Fields and Properties.

Methods - these define the actions that a class can perform by actioning a series of statements. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter. 


Events - a way of providing notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered using delegates. 


Delegates - a type safe container of one or more function pointers.


Operators - these are terms or symbols such as +, *, <, and so on that perform operations on operands. Operators can be redefined to perform operations on custom data types.  


Indexers - these allow an object to be indexed in a manner similar to arrays.  

Constructors - methods that are called when the object is first created. They are often used to initialize the object's data.

Destructors - methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which need to be released are handled appropriately.
 

Constants - data members that are known at compile time.


 
 

Pointers, Call by Value & Reference

Pointers : 

C# also supports pointers in a limited extent. A pointer is nothing but a variable that holds the memory address of another type. But in C# pointer can only be declared to hold the memory address of value types and arrays. Unlike reference types, pointer types are not tracked by the default garbage collection mechanism. For the same reason pointers are not allowed to point to a reference type or even to a structure type which contains a reference type. We can say that pointers can point to only unmanaged types which includes all basic data types, enum types, other pointer types and structs which contain only unmanaged types.  


The general form of declaring a pointer type is as shown below 
       
type *variable_name;  

Where * is known as the de-reference operator. For example the following statement 

int *x ; 
Declares a pointer variable x, which can hold the address of an int type. The reference operator (&) can be used to get the memory address of a variable.  

int x = 100; 

The &x gives the memory address of the variable x, which we can assign to a pointer variable
 
int *ptr = & x;.

Console.WriteLine((int)ptr) // Displays the memory addressConsole.WriteLine(*ptr) // Displays the value at the memory address. Unsafe Codes :

The C# statements can be executed either as in a safe or in an unsafe context. The statements marked as unsafe by using the keyword unsafe runs out side the control of Garbage Collector. Remember that in C# any code involving pointers requires an unsafe context. 
We can use the unsafe keyword in two different ways. It can be used as a modifier to a method, property, and constructor etc. For example          using System;
class MyClass
{
static void Main(string[] args)
        {
            unsafe
            {
                int a = 10;
                int* ptr = &a;  //pointer valriable
                Console.WriteLine("value of a :" + (*ptr));
                Console.WriteLine("address of a :"+(int)ptr);
                Console.Read();
            }
        }




Pointers & ConversionsIn C# pointer types do not inherit from object and no conversion exists between pointer types and objects. That means boxing and un-boxing are not supported by pointers. But C# supports conversions between the different pointer types and pointer types and integral types. 
C# supports both implicit and explicit pointer conversions within un-safe context. The implicit conversions are

  1. From any type pointer type to void * type.
  2. From null type to any pointer type.
The cast operator (()) is necessary for any explicit type conversions. The explicit type conversions are
  1. From any pointer type to any other pointer type.
  2. From sbyte, byte, short, ushort, int, uint, long, ulong to any pointer type.
  3. From any pointer type to sbyte, byte, short, ushort, int, uint, long, ulong types.
For example

char c = 'R';
char *pc = &c;
void *pv = pc; // Implicit conversionint *pi = (int *) pv; // Explicit conversion using casting operator 


Call by Value : 

In call by value method, the called function creates a new set of variables and copies the values of arguments into them.

To be more precise any changes that take place inside the calling method have no affect on the original value of the variable.Look the example below.Here in our example original value of a is 10 .When it is passed to "callByValue" method a is incremented.But it is not reflected in the main method and hence the final value of a remains same ie 10.

Pass by Reference: 


Any changes that take place inside the calling method will affect the original value of the variable."ref" keyword must be used in the calling method & called method.


Here in our example original value of a is 10 .When it is passed to "callByRef" method, a is incremented and also reflected in the main method and hence the final value of a is 20.
 Example :

public static void callByValue(int x)
        {
            x = x + x;
            Console.WriteLine("Sum : " + x);
        }
        public static void callByRef(ref int x)
        {
             x=x+x;
            Console.WriteLine("Sum : " + x);
        }
        static void Main(string[] args)
        {
                int a = 10;
                callByValue(a);
                Console.WriteLine("a value after call by val :" + a);
                callByRef(ref a);
                Console.WriteLine("a value after callby Ref :" + a);
                Console.Read();
            }
          
        }


Monday, September 10, 2012

Loops in C#

Iteration statements in C# :
1. Do While
2.While
2.For 
4.Foreach

Above all statements keep on executing repeatedly based on given condition.Till the given condition becomes false, loop keep on executing.

More Deep into the loops :

In my experience, there are two kinds of programmers. Those who write something to get the work done and those who want to write good code. But, here we get a big question. What is good code? Good code comes from good programming practices. What are good programming practices? Actually, my aim here is not to talk about good programming practices (I’m planning to write something related to that in future!), rather to talk more about writing something which will be more effective. I'm only going to look more deeper of two loops which are commonly used nowadays, and their differences in the aspect of performance.

Difference between Do while and While :

The difference between "do while" and "While " is that a "do while" loops while the test case is true, whereas " While " loops UNTIL the test case is true (which is equivalent to looping while the test case is false).

The difference between a "do ...while" loop and a "while {} " loop is that the while loop tests its condition before execution of the contents of the loop begins; the "do" loop tests its condition after it's been executed at least once. As noted above, if the test condition is false as the while loop is entered the block of code is never executed. Since the condition is tested at the bottom of a do loop, its block of code is always executed at least once.

To further clear your concept on this, understand the syntax and description of the two loop types:
while
The while loop is used to execute a block of code as long as some condition is true. If the condition is false from the start the block of code is not executed at all. The while loop tests the condition before it's executed so sometimes the loop may never be executed if initially the condition is not met. Its syntax is as follows.


while (tested condition is satisfied)
{
block of code
}


In all constructs, curly braces should only be used if the construct is to execute more than one line of code. The above program executes only one line of code so it not really necessary (same rules apply to if...else constructs) but you can use it to make the program seem more understandable or readable.
Here is a simple example of the use of the while loop. This program counts from 1 to 100.

using system;

static void Main()
{
int count = 1;

while (count <= 100)
{
Console.WriteLine(count);
count += 1; // Notice this statement
}

}
 
Note that no semi-colons ( ; ) are to be used after the while (condition) statement. These loops are very useful because the condition is tested before execution begins. However i never seem to like these loops as they are not as clear to read as the do ...while loops. The while loop is the favorite amongst most programmers but as for me, i definitely prefer the do ...while loop.

do ....while
 
The do loop also executes a block of code as long as a condition is satisfied.

Again, The difference between a "do ...while" loop and a "while {} " loop is that the while loop tests its condition before execution of the contents of the loop begins; the "do" loop tests its condition after it's been executed at least once. As noted above, if the test condition is false as the while loop is entered the block of code is never executed. Since the condition is tested at the bottom of a do loop, its block of code is always executed at least once.
Some people don't like these loops because it is always executed at least once. When i ask them "so what?", they normally reply that the loop executes even if the data is incorrect. Basically because the loop is always executed, it will execute no matter what value or type of data is supposed to be required. The "do ....while" loops syntax is as follows
do
{
block of code
} while (condition is satisfied);

Note that a semi-colon ( ; ) must be used at the end of the do ...while loop. This semi-colon is needed because it instructs whether the while (condition) statement is the beginning of a while loop or the end of a do ...while loop. Here is an example of the use of a do loop. 


using system;
static void Main()
{
int number;
      do

Console.WriteLine("Enter a number");
 number=convert.toint32(console.ReadLine());

    while(number%2==0)
{
Console.ReadLine("Entered number is even");
}    


}

Difference between For and Foreach : 

I’m going to take a very small piece of code for two popular looping statements for and foreach. We will look some code and will see what it does, more in detail about the functionality. 

 ********************using for loop  *****************************
int[] myInterger = new int[1];
int total = 0;
for(int i = 0; i < myInterger.Length; i++)
{
    total += myInterger[i];
}

*******************using foreach loop   ***************************

int[] myInterger = new int[1];
int total = 0;
foreach(int i in myInterger) 
{
    total += i;
}

Both codes will produce the same result. foreach is used on top of collections to traverse through while for can be used on anything for the same purpose. I’m not going to explain whatsoever about the code. Before going in more deeper, I think all of you are familiar with ILDasm which is used to generate IL code, and CorDbg tool which is normally used to generate JIT compiled code.
The IL code produced by C# compiler is optimized up to certain extend, while leaving some part to JIT. Anyway, this is not really what matters to us. So, when we talk about the optimization, two things we must consider. First is C# compiler and the second is JIT.

So, rather than looking more deep into IL code, we will see more about the code which is emitted by JIT. That is the code which will run on our machine. I’m now using AMD Athlon 1900+. The code highly depends on our hardware. Therefore, what you may get from your machine may differ from mine up to a certain extend. Anyway, the algorithms wont change that much.

In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array). When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn't care of that part.
Here, I’m going into the exact difference between the codes.

 FOR

cmp     dword ptr [eax+4],0           i<myInterger.Length
jle     0000000F
mov     ecx,dword ptr [eax+edx*4+8]   total += myInterger[i]
inc     edx                           ++i
cmp     esi,dword ptr [eax+4]         i<myInterger.Length
jl      FFFFFFF8
 
I’ll explain what is happening here. The esi register which holds the value of i and the length of myInteger array are compared at two stages. The first one is done only once to check the condition and if the loop can continue, the value is added. For the loop, it is done at the second stage. Inside the loop, it is well optimized and as explained, the work is done with perfect optimization.

foreach


cmp     esi,dword ptr [ebx+4]          i<myInterger.Length
jl      FFFFFFE3
cmp     esi,dword ptr [ebx+4]          i<myInterger.Length 
jb      00000009
mov     eax,dword ptr [ebx+esi*4+8] 
mov     dword ptr [ebp-0Ch],eax  
mov     eax,dword ptr [ebp-0Ch]
add     dword ptr [ebp-8],eax          total += i
inc     esi                            ++i
cmp     esi,dword ptr [ebx+4]          i<myInterger.Length
jl      FFFFFFE3
Anyone will say that both are not the same. But we will look why it differs from the for loop. The main reason for the difference is that both of them are differently understood by the compiler. The algorithm they are using is different. Two compare statements one after the other is unnecessary. It is doing the same thing again and again for no reason!
cmp                    esi,dword ptr [ebx+4]   
jl                         FFFFFFE3
cmp                    esi,dword ptr [ebx+4]
It also uses some unnecessary move statements which also may (not always, but depends) reduce the performance of the code. foreach is thinking everything as a collection and treating them as a collection. I feel, that will also reduce the performance of the work.
Therefore, I strongly feel if you are planning to write high performance code that is not for collections, use for loop. Even for collections, foreach may look handy when using, but it's not that efficient. Therefore, I strongly recommend everyone to use for loop rather than foreach at any stage.

Arrays Part -2


Array Class
Array class is the mother of all arrays and provides functionality for creating, manipulating, searching, and sorting arrays in .NET Framework.
 
Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class that means we cannot create an instance of the Array class.
 
Creating an Array
 
Array class provides the CreateInstance method to construct an array. The CreateInstance method takes first parameter as the type of items and second and third parameters are the dimension and their range. Once an array is created, we use SetValue method to add items to an array.
 
The following code snippet creates an array and adds three items to the array. As you can see the type of the array items is string and range is 3. You will get an error message if you try to add 4th item to the array.
 
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("Mahesh Chand", 0);
stringArray.SetValue("Raj Kumar", 1);
stringArray.SetValue("Neel Beniwal", 2);
 
Note: Calling SetValue on an existing item of an array overrides the previous item value with the new value.
 
The code snippet in Listing 2 creates a multi-dimensional array.
 
Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);
for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++)
    for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)
        for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++)
        {
            intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k);
        }
 
foreach (int ival in intArray3D)
{
    Console.WriteLine(ival);
}
Listing 2
Array Properties
 
Table 1 describes Array class properties. 
 
IsFixedSize
Return a value indicating if an array has a fixed size or not.
IsReadOnly
Returns a value indicating if an array is read-only or not.
LongLength
Returns a 64-bit integer that represents total number of items in all the dimensions of an array.
Length
Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.
Rank
Returns the number of dimensions of an array.
 
Table 1

The code snippet in Listing 3 creates an array and uses Array properties to display property values.
 
int[] intArray = new int[3] {0, 1, 2};
if(intArray.IsFixedSize)
{
    Console.WriteLine("Array is fixed size");
    Console.WriteLine("Size :" + intArray.Length.ToString());
    Console.WriteLine("Rank :" + intArray.Rank.ToString());
}
Listing 3
The output of Listing looks like Figure 2.
 
arrays2.png
Figure 2
Searching for an Item in an Array
The BinarySearch static method of Array class can be used to search for an item in an array. This method uses the binary search algorithm to search for an item. The method takes at least two parameters. First parameter is the array in which you would like to search and the second parameter is an object that is the item you are looking for. If an item is found in the array, the method returns the index of that item (based on first item as 0th item). Otherwise method returns a negative value.

Note: You must sort an array before searching. See comments in this article.

Listing 4 uses BinarySearch method to search an array for a string.
 
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");
Listing 4
Sorting Items in an Array
The Sort static method of the Array class can be used to sort array items. This method has many overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the Sort method to sort array items. Using the Sort method, you can also sort a partial list of items.
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");
 
Console.WriteLine();
 
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Sorted Array");
Console.WriteLine("---------------------");
Array.Sort(stringArray);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 5
The output of Listing 5 looks like Figure 3.
arrays3.png
Figure 3
Alternatively the Sort method takes starting index and number of items after that index. The following code snippet sorts 3 items starting at 2nd position.
Array.Sort(stringArray, 2, 3);

The new output looks like Figure 4.
arrays4.png
Figure 4
Getting and Setting Values
The GetValue and SetValue methods of the Array class can be used to get and set values of an array's items. The code listed in Listing 4 creates a 2-dimensional array instance using the CreateInstance method. After that I use the SetValue method to add values to the array. 
In the end, I find number of items in both dimensions and use GetValue method to read values and display on the console. 
Array names = Array.CreateInstance(typeof(String), 2, 4);
names.SetValue("Rosy", 0, 0);
names.SetValue("Amy", 0, 1);
names.SetValue("Peter", 0, 2);
names.SetValue("Albert", 0, 3);
names.SetValue("Mel", 1, 0);
names.SetValue("Mongee", 1, 1);
names.SetValue("Luma", 1, 2);
names.SetValue("Lara", 1, 3);
int items1 = names.GetLength(0);
int items2 = names.GetLength(1);
for (int i = 0; i < items1; i++)
    for (int j = 0; j < items2; j++)
        Console.WriteLine(i.ToString() + "," + j.ToString() + ": " + names.GetValue(i, j));
Listing 6
The output of Listing 6 generates Figure 5.
arrays5.png
Figure 5
Reverse an array items
The Reverse static method of the Array class reverses the order of items in an array. Similar to the Sort method, you can just pass an array as a parameter of the Reverse method. 
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
           
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
//  Array.Sort(stringArray, 2, 3);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Double Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
//  Array.Sort(stringArray, 2, 3);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 7
The output of Listing 7 generates Figure 6.
 
arrays6.png
Figure 6
Clear an array items
The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is number of elements. The following code clears two elements from the array starting at index 1 (means second element of the array). 
Array.Clear(stringArray, 1, 2);
Note: Keep in mind, the Clear method does not delete items. Just clear the values of the items.
The code listed in Listing 8 clears two items from the index 1.
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Clear Items");
Console.WriteLine("---------------------");
Array.Clear(stringArray, 1, 2);
 
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 8
The output of Listing 8 generates Figure 7. As you can see from Figure 7, the values of two items from the output are missing but actual items are there.
arrays7.png
Figure 7
Get the size of an array
The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods. 
Console.WriteLine(stringArray.GetLength(0).ToString());
Console.WriteLine(stringArray.GetLowerBound(0).ToString());
Console.WriteLine(stringArray.GetUpperBound(0).ToString()); 

Copy an array
The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types. 
// Creates and initializes a new Array of type Int32.
Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5);
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
// Creates and initializes a new Array of type Object.
Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);
Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);
int items1 = objArray.GetUpperBound(0);
for (int i = 0; i < items1; i++)
    Console.WriteLine(objArray.GetValue(i).ToString());
Listing 9
You can even copy a part of an array to another array by passing the number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
public static void Copy(Array, int, Array, int, int);
Clone an Array
Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
The following code snippet creates a cloned copy of an array of strings.
string[] clonedArray = (string[])stringArray.Clone();