How about:
class TSOC<TCollection, TValue> : ICollection<TValue>, INotifyCollectionChanged
where TCollection : ICollection<TValue>
{
private TCollection collection;
}
I think this is what you're looking for. It seems like maybe you're trying to wrap a generic collection, and you want the first type of parameter to be an existing collection of the same type. This will give you exactly that.
Hard to say, but you might not even need that. Unless you really need to know the underlying type of the TCollection
object, you could probably just make it a TSOC<TValue>
and accept an ICollection<TValue>
to wrap it with:
class TSOC<TValue> : ICollection<TValue>, INotifyCollectionChanged
{
private ICollection<TValue> collection;
}
This is functionally the same thing, you just won't have knowledge of the actual underlying type of the ICollection<TValue>
.
Update:
Responding now to this edit:
Basically I just wanted to wrap all the ICollection methods in locks and force them to run on a particular thread, but still keep all the additional functionality of the programmer's collection of choice.... I'm not sure this is possible though
I think you actually could achieve what you want, but perhaps in a slightly different way than you expect. You don't even really need the collection, you just want a synchronized wrapper:
public class Synchronized<T>
{
private readonly object sync = new Object();
private T item;
public Synchronized(T item)
{
this.item = item;
}
public void Execute(Action<T> action)
{
lock (sync)
action(item);
}
public TResult Evaluate<TResult>(Func<T, TResult> selector)
{
lock (sync)
return selector(item);
}
}
Then use it as:
var sc = new Synchronized<ICollection<int>>(new List<int>());
sc.Execute(c => c.Add(3));
int count = sc.Evaluate(c => c.Count);
Now I know this isn't exactly what you want, since it doesn't actually give you an instance of ICollection<T>
you can pass around. But it's a clean encapsulation of the locking behaviour and hides the inner collection, so you can guarantee that every operation is "thread safe."
If you really, really need an equivalent instance of ICollection<T>
that wraps another ICollection<T>
while adding thread safety, then what you're actually looking for is method interception using a library like Castle DynamicProxy.