/// <summary>
/// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers.
/// </summary>
/// <param name="type">A Type that represents the element type of the array.</param>
/// <param name="initializers">The expressions used to create the array elements.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayInit(Type type, IEnumerable <Expression> initializers)
{
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
if (type == typeof(void))
{
throw Error.ArgumentCannotBeOfTypeVoid(nameof(type));
}
TypeUtils.ValidateType(type, nameof(type));
if (type.IsByRef)
{
throw Error.TypeMustNotBeByRef(nameof(type));
}
if (type.IsPointer)
{
throw Error.TypeMustNotBePointer(nameof(type));
}
ReadOnlyCollection <Expression> initializerList = initializers.ToReadOnly();
Expression[] newList = null;
for (int i = 0, n = initializerList.Count; i < n; i++)
{
Expression expr = initializerList[i];
RequiresCanRead(expr, nameof(initializers), i);
if (!TypeUtils.AreReferenceAssignable(type, expr.Type))
{
if (!TryQuote(type, ref expr))
{
throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type);
}
if (newList == null)
{
newList = new Expression[initializerList.Count];
for (int j = 0; j < i; j++)
{
newList[j] = initializerList[j];
}
}
}
if (newList != null)
{
newList[i] = expr;
}
}
if (newList != null)
{
initializerList = new TrueReadOnlyCollection <Expression>(newList);
}
return(NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList));
}