I have a worker class that does stuff with a collection of objects. I need each of those objects to have two properties, one has an unknown type and one has to be a number.
I wanted to use an interface so that I could have multiple item classes that allowed for other properties but were forced to have the PropA and PropB that the worker class requires.
This is the code I have so far, which seemed to be OK until I tried to use it. A list of MyItem is not allowed to be passed as a list of IItem even though MyItem implements IItem. This is where I got confused.
Also, if possible, it would be great if when instantiating the worker class I don't need to pass in the T, instead it would know what T is based on the type of PropA.
Can someone help get me sorted out? Thanks!
public interface IItem<T>
{
T PropA { get; set; }
decimal PropB { get; set; }
}
public class MyItem : IItem<string>
{
public string PropA { get; set; }
public decimal PropB { get; set; }
}
public class WorkerClass<T>
{
private List<T> _list;
public WorkerClass(IEnumerable<IItem<T>> items)
{
doStuff(items);
}
public T ReturnAnItem()
{
return _list[0];
}
private void doStuff(IEnumerable<IItem<T>> items)
{
foreach (IItem<T> item in items)
{
_list.Add(item.PropA);
}
}
}
public void usage()
{
IEnumerable<MyItem> list= GetItems();
var worker = new WorkerClass<string>(list);//Not Allowed
}