Jack Malkovich
Jack Malkovich

Reputation: 806

Reflection: Cast Array Of Objects To List

Code:

object arrayOfObjs = new object[]{ 1, "test"};

Now I want to Add new element to this array. Is it possible like:

((IEnumerable)arrayOfObjs).Cast<object>().ToList().Add("test123");

This code doesn't add item.

Edit:

if we will make it strongly typed:

object arrayOfObjs = new string[]{ "1", "test"};

Adding work, thx:

var tmp = ((IEnumerable)arrayOfObjs).Cast<object>().ToList();
tmp.Add("test123");

How can we cast this list back to Array of T, if type is unknown at design time?

Upvotes: 0

Views: 200

Answers (1)

Alex
Alex

Reputation: 35407

You'd need to capture the result in a local variable:

var items = ((IEnumerable)arrayOfObjs).Cast<object>().ToList();

items.Add("test123");

Upvotes: 3

Related Questions