How to use Array.CreateInstance() method to initializes a new instance of the Array class in C#

2 Answers

0 votes
using System;
using System.Collections;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Array intArray = Array.CreateInstance(typeof(System.Int32), 5);
            for (int i = intArray.GetLowerBound(0); i <= intArray.GetUpperBound(0); i++)
                intArray.SetValue(i + 10, i);

            PrintArray(intArray);
        }
        public static void PrintArray(Array arr)
        {
            IEnumerator enumerator = arr.GetEnumerator();
            int i = 0;
            int cols = arr.GetLength(arr.Rank - 1);
            while (enumerator.MoveNext())
            {
                if (i < cols)
                {
                    i++;
                }
                else
                {
                    Console.WriteLine();
                    i = 1;
                }
                Console.Write("\t{0}", enumerator.Current);
            }
            Console.WriteLine();
        }
    }
}


/*
run:
 
        10      11      12      13      14

*/

 



answered Apr 15, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Array intArray = Array.CreateInstance(typeof(System.Int32), 5);
            for (int i = intArray.GetLowerBound(0); i <= intArray.GetUpperBound(0); i++)
                intArray.SetValue(i + 10, i);

            PrintArray(intArray);
        }
        public static void PrintArray(Array arr)
        {
            for (int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0); i++)
                Console.WriteLine("arr[{0}] = {1}", i, arr.GetValue(i));
        }
    }
}


/*
run:
 
arr[0] = 10
arr[1] = 11
arr[2] = 12
arr[3] = 13
arr[4] = 14

*/

 



answered Apr 15, 2016 by avibootz
...