Search code examples
c#activator

Convert array type to singular


In C# is it possible to convert an array type to singular - for use with Activator.CreateInstance. Take this for example:

void Main()
{
    var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
    var objects = new List<object>();

    foreach (var type in types)
    {
        // possibly convert type here? (from array to singular - type[] to type) 

        Debug.WriteLine($"{type}");
        objects.Add(Activator.CreateInstance(type));
    }
}

// Define other methods and classes here

public class ExampleClass
{
    public int X;
    public int Y;
}

Gets the following output:

LINQPad output


Solution

  • Found this works:

    void Main()
    {
        var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
        var objects = new List<object>();
    
        foreach (var type in types)
        {
            Debug.WriteLine($"{type}");
            objects.Add(type.IsArray
                        ? Activator.CreateInstance(type, 1)
                        : Activator.CreateInstance(type));
        }
    }
    
    // Define other methods and classes here
    
    public class ExampleClass
    {
        public int X;
        public int Y;
    }