I have the following classes:
class Item { }
class MeetingItem : Item { }
class ItemGroup<T> { }
now, this works without an issue:
Item something;
something = new MeetingItem();
this however fails:
ItemGroup<Item> itemGroup;
itemGroup = new ItemGroup<MeetingItem>(); // Fails here
I'm getting the "Cannot Implicitly convert type 'ItemGroup<MeetingItem>
' to 'ItemGroup<Item>
'" error. Isn't that exactly what I'm doing above (assigning something to the type Item and then instantiating to MeetingItem)?
What I will have eventually is a collection of Items in the ItemGroup class along with a few other members. And then I'm going to have a collection of ItemGroups that will contain different types of derived Items. Ideally I'd like to have Item as an abstract class (maybe an interface, I might need to keep it a class depending on what I need to implement).
I'm open to any refactoring ideas.
Thanks.
Edit to add my solution without having a Generic ItemGroup: I decided to ditch generics... kinda... I cobbled together this:
public class ItemGroup {
public Type ItemType => this.Items.GetType().GetGenericArguments()[0];
public IList Items { get; set; }
public ItemGroup(Type itemType) {
var genericListType = typeof(List<>).MakeGenericType(itemType);
Items = (IList)Activator.CreateInstance(genericListType);
}
}
So, I can now do something like this:
List<ItemGroup> groups = new List<ItemGroup>();
groups.Add(new ItemGroup(typeof(MeetingItem));
and then I can test for the specific Item type by the following:
groups[0].ItemType == typeof(MeetingItem)
It seems a little hacky, but it works. I'm a little concerned about performance on the ItemType Property, and I'm open to any refactoring ideas.