Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

Casting List<SomeClass> to List<object>

Can we cast List<SomeClass> in to List<object> int .net.

Upvotes: 2

Views: 137

Answers (4)

itsmatt
itsmatt

Reputation: 31416

What about:

List<object> listObj = myList.ConvertAll(item => (object)item);

I made a simple Person class like so:

class Person
{
    public string Name { get; set; }
    public double Score { get; set; }
}

Made a list:

List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Al",  Score=97.3});
people.Add(new Person() { Name = "Bob",  Score = 99.2});
people.Add(new Person() { Name = "Charlie", Score=55.333});

And did the conversion like this:

List<object> listOfObjects = people.ConvertAll(item => (object)item);

Seemed to work well enough. But perhaps I'm missing something here. Obviously, I've created a new list here. Thoughts?

Upvotes: 0

Edgar
Edgar

Reputation: 21

As an example this should work

List<int> intList=new List<int>();
intList.Add(1);
intList.Add(2);
List<object> listObject = intList.Cast<object>().ToList();

Upvotes: 0

Guffa
Guffa

Reputation: 700910

No, You can cast an array that way, but not a list.

As SomeClass can always be cast to object, you can use the Cast method to create the list:

List<object> list = someClassList.Cast<object>().ToList();

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 416159

You can't do it with a simple cast. They are two different types, and there is no inheritance relationship between the two types. But you can do something like this:

foreach (Object item in MyList.Cast<object>() )
{
     //...
}

Upvotes: 3

Related Questions