none
Conversion from array to object[] RRS feed

  • Question

  • class Class1
    {
    static void Main(string[] args)
            {
                //change the baseindex and see objArray value.
                int baseIndex = 1;
               
                object arrayWrappedIntoObject = Class1.CreateAndInitializeNonZeroIndexBasedArray(baseIndex);
                
                Object[] objArray =  arrayWrappedIntoObject as object[];
                Console.WriteLine("why it is null or nonnull (watch for non zero index based array)?" + objArray);
                
                System.Array array =  arrayWrappedIntoObject as System.Array;
                Console.WriteLine("here it an obvious array " + array);
                
            }

            private static object CreateAndInitializeNonZeroIndexBasedArray(int baseIndex)
            {
                int[] length = new int[1];
                int[] lowerBounds = new int[1];
                length[0] = 1;
                lowerBounds[0] = baseIndex;
              
                System.Array arr =  Array.CreateInstance(typeof(string),length, lowerBounds);
                arr.SetValue("foo", baseIndex);

                //when comment this, uncomment all code after this line.
                //uncomment this for flow 1.
                return arr;
                
                //uncomment this for flow 2.
    //            string[] strArr = new string[1];
    //            arr.CopyTo(strArr, 0);
    //            return strArr;
            }

    }

    There are two different "type conversion" flows

    flow 1. System.Array to object   and   object to object[]             [Question. why null?]
    flow 2. System.Array to string[]   and   string[] to object   and   object to object[]             [Question. why not null?]
    Friday, December 7, 2007 7:54 PM

Answers

  • you need to initialize the target object[]

    try this:

                int baseIndex = 1;

                int[] length = new int[1];
                int[] lowerBounds = new int[1];
                length[0] = 1;
                lowerBounds[0] = baseIndex;

                System.Array arr = Array.CreateInstance(typeof(string), length, lowerBounds);
                arr.SetValue("foo", baseIndex);

                object[] test = new object[arr.Length];
                arr.CopyTo(test, 0);
    Friday, December 7, 2007 8:42 PM