Tuesday, 5 June 2012

Dynamic Sized Arrays in C#

In Static Arrays Array size should be defined at compile time.  In some cases programmer may not know exact size of the array.  At that time, Programer can create dynamic arrays using following code.

       Array dynamicSizeArray= Array.CreateInstance(typeof(string), 2);
       dynamicSizeArray.SetValue("World", 1);

        Console .Write(dynamicSizeArray.GetUpperBound(0));

The above code Creates  an Single Dimensional Array of size 2  of type string.
0th location holds Hello
1st location holds World

GetLength method returns 2
GetUpperBound return 1.

Note: Programmer can create multi-dimenstional arrays using Array.CreateInstance method