How to declare function that accepts any generic list as input parameter?

M

marss

How to declare function that accepts any generic list as input
parameter? I mean I need
void foo(List<> list)
{
}
where:
Valid parameters are List<SomeInfo>, List<string>, List<Guid>, e.t.c.
Invalid parameters are SomeInfo[], string[], Array, ArrayList,
Dictionary<int, string>, e.t.c

Is it possible?

TIA,
Mykola
http://marss.co.ua
 
J

Jon Skeet [C# MVP]

How to declare function that accepts any generic list as input
parameter? I mean I need
void foo(List<> list)
{}

where:
Valid parameters are List<SomeInfo>, List<string>, List<Guid>, e.t.c.
Invalid parameters are SomeInfo[], string[], Array, ArrayList,
Dictionary<int, string>, e.t.c

Is it possible?

Yes - you need to make the method generic:

void Foo<T>(List<T> list)
{
}

Jon
 
M

marss

How to declare function that accepts any generic list as input
parameter? I mean I need
void foo(List<> list)
{}
where:
Valid parameters are List<SomeInfo>, List<string>, List<Guid>, e.t.c.
Invalid parameters are SomeInfo[], string[], Array, ArrayList,
Dictionary<int, string>, e.t.c
Is it possible?

Yes - you need to make the method generic:

void Foo<T>(List<T> list)
{

}

Jon

Thanks
 
M

Marc Gravell

Invalid parameters are SomeInfo[], string[], Array, ArrayList,
For info, if you want it to additionally work with arrays [i.e. T[],
not Array], (typed) collections, etc - then another option is to use
the less specific IList<T> interface:

void Foo<T>(IList<T> list)
{
}

This obviously won't give you as many methods etc as List<T>, but it
should allow most options. In .NET 3.5, extension methods (in
System.Linq) mean that IList<T> exposes almost as much functionality
as List<T> does (albeit via subtly different implementation).

Marc
 
M

marss

Valid parameters are List<SomeInfo>, List<string>, List<Guid>, e.t.c.
Invalid parameters are SomeInfo[], string[], Array, ArrayList,

For info, if you want it to additionally work with arrays [i.e. T[],
not Array], (typed) collections, etc - then another option is to use
the less specific IList<T> interface:

void Foo<T>(IList<T> list)
{

}

This obviously won't give you as many methods etc as List<T>, but it
should allow most options. In .NET 3.5, extension methods (in
System.Linq) mean that IList<T> exposes almost as much functionality
as List<T> does (albeit via subtly different implementation).

Marc

Thanks for suggestion
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top