wolen wolen - 3 years ago 73
C# Question

Convert List<T> to List<object>

I have a problem with the generic class. I have something like this:

public abstract class IGroup<T> : IEnumerable where T : class {

protected List<T> groupMembers;
protected List<IGameAction> groupIGameActionList;

public IGroup() {
groupMembers = new List<T>();

groupIGameActionList = new List<IGameAction>();
//groupIGameActionList.Add(new DieGameAction(groupMembers));

And second class:

class DieGameAction : IGameAction {

List<object> gameObjectList;

public DieGameAction(List<object> objectList) {
gameObjectList = objectList;

I don't know how to cast or convert
in commented line. This doesn't work because it can not be converted (
). So how can I do it?

Answer Source

But that doesn't look a good thing to do. You are creating a new empty list that will not be related to the original anymore.

The way you're gonna be using these classes will tell if that would be a good idea. If you're planning to have both lists updated by adding items to a single class, it will not fit. Then maybe your DieGameAction should be generic as well: DieGameAction<T>. Then you could give the original list without casting.

But, there's another danger: if you set a new list to the IGroup, it will not be reflected to DieGameAction.

So, it all depends on what you're trying to do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download