C# – Why can’t new[] {AnonymousType, AnonymousType} be casted to IEnumerable

anonymous-typesc

I have an array of an anonymous type declared as:

var list = new[] 
{
    new {Name = "A", Age = 10},
    new {Name = "B", Age = 15}
}

Now list inherits from type Array, which implements IEnumerable. Why does the following fail:

Convert.ChangeType(list, typeof(IEnumerable));

This also fails:

Convert.ChangeType(list, typeof(Array));

Kind regards,

Best Answer

The Convert.ChangeType method requires an implementation of IConvertible - essentially a declaration of how to convert from the source type to the target type. System.Array does not implement the IConvertible interface.

What you are trying to do is cast from one type to another, and (IEnumerable)list works perfectly well.

Edit:

As Jon says, the cast here is implicit, so simple assignment (ie implicit cast) to an IEnumerable also works.