views:

210

answers:

1
+1  Q: 

Nested Generics

I have asked this before but I didn't get the question right so the answer was missed.

If I have a method that returns an ObservableColletion<T> how would I then use this in another generic method.

Would

method2<ObservableCollection<T>>(){}

be the way to go.

I am trying to make a generic resultEventArgs that will pass the results of an Ado.NET Dataservices query to all subscribers. Inside that I want ot be able to pass the strongly typed EntityCollection that is returned [Ado.NET 1.5 generated]

So yes, my question is worded ObservableCollection because i didn't want to get the whole ado.net dataservices confusion.

Cheers Dave

+1  A: 

It depends; do you want to specify the item type, or the collection type? If you just want to specify the item, then the T relates just to the item:

public ObservableCollection<T> SomeMethod<T>()
{
    var data = new ObservableCollection<T>();
    data.Add(default(T)); // or whatever
    return data;
}

Then you can use ObservableCollection<Order> orders = SomeMethod<Order>() etc. If you need to specify the collection type, you may need more generic types...

public TList SomeMethod<TList, T>()
    where TList : class, IList<T>, new()
{
    var data = new TList();
    data.Add(default(T)); // or whatever
    return data;
}

However, calling it is trickier. It can't do type inference unless the list is an argument, meaning you have to specify both TList and T when calling it... not pretty.

Marc Gravell
Marc,Accepted this since it gives the truth of the matter and the 'where' I have seen through some MSDN. It does look messy, but surely the xplosion of classes for each of my 140 entities would be as painful.If I study this I think I can make my resultEventArgs class as polymorphic as I need. The alternative is to assume the return type and cast it to the entity and then the methods/properties will be available, but I think then I am sailing some dodgy path.
DavidA