Difference between Array.CreateInstance and using the new operator to create new array instance

I can see following two ways of instantiating an int array in C#:

  1. Through an API in System.Array abstract class:

    var arrayInstance = Array.CreateInstance(typeof(int), 4);
    
  2. Through various array initialization syntax:

    var arrayInstanceWithSyntax = new int[4];
    

Are the above two ways absolutely identical? Does the compiler converts the second syntax into first syntax at compile time itself (present in MSIL) or there is some JIT magic at CLR level which happens at run time or there is no conversion at all between the two code syntax?

Jon Skeet
people
quotationmark

They definitely create the same kind of value - unlike if you call Array.CreateInstance and create an array with a non-zero lower bound, for example.

However, they're not the same in terms of IL - the first is simply a method call, the second uses the newarr IL instruction.

There doesn't need to be any kind of "JIT magic" here - there are just two paths to create the same kind of value.

The compile-time type of your first variable is just Array though - you'd have to cast it to int[] for the two pieces of code to really have the same result.

I would always use the "C# native" array creation syntax where possible - only use Array.CreateInstance when you have an element Type for some reason (rather than knowing at compile time, even via a generic type parameter)... or if you're trying to create an array that may have a non-zero lower bound.

people

See more on this question at Stackoverflow