views:

108

answers:

2

Hi,

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,

+4  A: 

Just use the implicit conversion and it's fine:

IEnumerable enumerable = list;

As Nader says, Convert.ChangeType works with IConvertible. Personally I can't remember the last time I used it - I would stick with simple casts etc where possible.

Jon Skeet
+9  A: 

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.

Nader Shirazie
You don't even need a cast - the conversion is implicit.
Jon Skeet
True. Leaving the explicit cast example is just to point out how to do a cast, if that's what the op is trying to do.
Nader Shirazie