views:

86

answers:

3

I have a custom control which contains a list of objects. The control is instantiated by the visual designer and then configured in code. The control is a grid which displays a list of entities.

I have an initialise method like this.

public void Initialise(ISession session, Type type, ICollection<IPersistentObject> objs)

IPersistentObject is an interface. However this doesn't work when I want to assign a collection of something that implements IPersistentObject.

So I changed it to this.

public void Initialise<T>(ISession session, Type type, ICollection<T> objs) where T : class, IPersistentObject

But now I want to assign the objs parameter to a member variable of type ICollection<IPersistentObject> which doesn't work.

I can't make the class generic because it is a control which can't have generic types AFAIK. I can't copy the collection because the control MUST modify the passed in collection, not take a copy and modify that.

What should I do?

A: 

You could change the member variable to a non-generic ICollection, and cast as appropriate.

Matt Howells
This is not robust since `ICollection<T>` doesn't inherit the non-generic `ICollection` interface. There could conceivably be a type that implements the first interface but not the latter.
Ani
+1  A: 

ICollection<T> does not support generic variance like that. As I see it, your options are:

  1. Code a wrapper around ICollection<T> that wraps a ICollection<IPersistentObject> and does the type-checking for you.
  2. Use IEnumerable<T> instead, which does support variance in the manner you describe.
  3. Use the non-generic IList, if your concrete classes implement it.
thecoop
Number 1 worked for me, thanks.
Mike Q
+3  A: 

If you do not need to the objs to be an actual collection (e.g. with Add/Remove methods etc..) then you could replace the ICollection with IEnumerable.

void Initialise(ISession session, Type type, IEnumerable<IPersistentObject> objs)
Fara
Sadly I need Add/Remove as the list will be modified by the control.
Mike Q