edosoft
edosoft

Reputation: 17281

How can I specifiy a generic collection as restriction in a generic method

Aloha

I have a method with (pseudo) signature:

public static T Parse<T>(string datadictionary) where T : List<U>

This doesn't build. How can I restrict the in the method to accept only generic List<> objects (which should of cource not contain T's but something else :)

I need to restrict the type of T because I need to call a method on it in this code. The type passed in is a custom collection (based on List).

public class MyCollection<T> : List<T> where T: MyClass, new()
{
    public void Foo();
}


public static T Parse<T>(string datadictionary) where T : MyCollection<U>
{
    T.Foo();
}

-Edoode

Upvotes: 3

Views: 430

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1064104

Assuming I read the question correctly, and you want to return T where T : List<U> (for some T and U)...

As an aside - subclassing List<T> isn't usually very useful... List<T> doesn't provide any useful virtual methods. Subclassing Collection<T> provides more flexibility. Of course, you can make your code not care, by simply coding against the IList<T> interface, perhaps adding : new() so you can create the list itself:

public static TList Parse<TList, TItem>(string datadictionary)
    where TList : IList<TItem>, new() {...}

Upvotes: 3

Pop Catalin
Pop Catalin

Reputation: 62990

You can also do this, without specifying a restriction of type List<u>

 public static List<T> Parse<T>(string datadictionary) ...

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503439

Well, you can have two type parameters:

public static T Parse<T, U>(string datadictionary) where T : List<U>

That way you'll also actually know what U is (in a compile-time manner)...

EDIT: Alternatively (and better), just specify the element type and change the return type:

public static List<T> Parse<T>(string datadictionary)

e.g.

List<int> data = Parse<int>(whatever);

Note that you may wish to change from List<T> to IList<T> or even a broader interface.

Upvotes: 8

Related Questions