I have list of user class but now i have to return it as a list of object, I try to convert it but it gives me error like. Can not implicitly convert.
Asked
Active
Viewed 1,813 times
0
-
2Why do you need to convert the list to a list of objects? – msarchet May 08 '10 at 06:03
-
@msarchet: probably to satisfy a third party library API requirement. It happens to me unfortunately rather frequently. – Randolpho May 08 '10 at 06:11
-
because my function return type if list – girish May 08 '10 at 06:13
3 Answers
7
The simplest solution in .NET 3.5 would be:
List<object> objects = users.Cast<object>().ToList();
Note that this will create a copy of the list. You can't view a List<User>
as a List<object>
- otherwise you'd be able to do:
objects.Add(new SomeOtherType());
which would clearly break things.
In C# 4, you can use the covariance of IEnumerable<T>
to make it slightly simpler:
List<object> objects = new List<object>(users);
or
List<object> objects = users.ToList<object>();

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
1
public List<Object> ConvertToObjectList<N>(List<N> sourceList)
{
List<Object> result = new List<Object>();
foreach(N item in sourceList)
{
result.Add(item as Object);
}
return result;
}
...
List<Object> myList = ConvertToObjectList<myClass>(myOldList);
I am not sure if I understood your question correctly, but here's my two cents.

Francisco Soto
- 10,277
- 2
- 37
- 46
0
=/ with linq?
var object_list = from o in user_list
select new {
User: o.User,
Guid: o.Guid
// insert properties here
}
??????

Germán Rodríguez
- 4,284
- 1
- 19
- 19