Search code examples
c#vb6-migration

C# Is there a way of declaring non zero lower bound array typeof(dynamic)


I need it to interface vb6 library which expects that form of output array to do some calculations on data. Is there any form of workaround since I cannot use statement typeof(dynamic) in array declaration only typeof(object)...

What I have tried so far:

System.Array Outputs = Array.CreateInstance(typeof(Object), 1);
System.Array Outputs = Array.CreateInstance(typeof(object), 1);
System.Array Outputs = Array.CreateInstance(typeof(dynamic), 1); // Compilation error

Solution

  • dynamic really only exists at compile-time. If you create a List<dynamic> for example, that's really creating a List<object>. As such, it doesn't make sense to use typeof(dynamic) which is why the third line fails to compile. If you're passing the array to other code, it's up to that other code how it uses the array - there's nothing that would exist at execution time to "know" that it's meant to be dynamically typed.

    But in order to create an array, you've got to provide a length. The overload of Array.CreateInstance you're using always uses a lower bound of zero. You want the overload accepting two arrays of integers - one for lengths and one for lower bounds. For example:

    using System;
    
    class Program
    {
        static void Main()
        {
            Array outputs = Array.CreateInstance(
                typeof(object), // Element type
                new[] { 5 },    // Lengths                                             
                new[] { 1 });   // Lower bounds
    
            for (int i = 1; i <= 5; i++)
            {
                outputs.SetValue($"Value {i}", i);
            }
            Console.WriteLine("Set indexes 1-5 successfully");
            // This will throw an exception
            outputs.SetValue("Bang", 0);        
        }
    }