views:

56

answers:

1

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
}
+3  A: 

You can make this work if you supply the interface directly instead of the concrete type. It just isn't able to do the implicit conversion for you:

IEnumerable<IItem<string>> items = GetItems().Cast<IItem<string>>();
var worker = new WorkerClass<string>(items);

On an aside: Your original code would actually work in C# 4, which supports covariance on IEnumerable<T>. But previous versions of C# don't, which is why you get the error.

Aaronaught
@Aaaronaught: interesting that programming languages now(at least in next version), make the programmers' code works that the programmer deemed should be working in the first place. love the improvements they made on C#. i'll read that covariance
Hao
That works, thank you! Is there a simpler way for me to approach this or am I on the right track?
Amy
@Amy: It's hard to say without really knowing what the `WorkerClass` does or what any of those `Item` objects are. It's certainly OK to derive a generic type/interface and further constrain it; I do this all the time.
Aaronaught