Click to See Complete Forum and Search --> : List<> Creation
hoagers34
May 31st, 2007, 11:43 AM
I am trying to create a List<> based upon a type that is sent in from a method call...but i am unable to create a list with the type variable. Can anyone point me in the right direction? Below is an example of what i am trying to accomplish:
public void foo(System.Type type)
{
List<type> list = new List<type>();
}
Thanks.
wildfrog
May 31st, 2007, 12:01 PM
I'm not sure if there is any good solution to what you want (alteast not without some strange reflection or emitted code).
Can you use a generic member function?
public void foo<T>(T t)
{
List<T> list = new List<T>();
//...
}
Anyway, such request often indicates a poor design (not saying that's the case here). But if you explain what problem you need to solve, someone might give you better alternatives.
- petter
hoagers34
May 31st, 2007, 12:11 PM
I think i may have found a solution.
public interface IBlah
{
}
public class Blah : IBlah
{
}
private void Foo( )
{
List<IBlah> list = new List<IBlah> ();
Blah a = new Blah ();
list.Add (a);
Blah c = (Blah)list[0];
}
hoagers34
May 31st, 2007, 12:14 PM
I have 10 or so classes and i am creating a webmethod that will query a database and return a list<> of objects of a specific class based upon the query. I was trying to find a way to have 1 webmethod that could return some sort of generic list based upon a supplied type (so i dont have to write 10 different webmethods).
I think the interface implementation i posted above will get me where i need to go.
Thanks for the suggestion.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.