OopsUser
OopsUser

Reputation: 4784

How to make a function that creates a generic list in C#

I have 4 tables in the DB, each one has Id and Name, but they represent different things. for each "thing" i have a different class, they all inherit from "thing". i have 4 functions :

List<thing1> getAllThings1();
List<thing2> getAllThings2();
List<thing3> getAllThings3();
List<thing4> getAllThings4();

each function reads from different table and creates the needed list.

Because i want to avoid code duplication i wanted to make a utility function that receives the table name (as string) and the type (thing1, thing2 ... etc), and returns List<t>.

unfortunately this is impossible (without reflection) : Create list of variable type

My current solution is that i have a function that returns a List, i call her in each "getAllThings#" and then manually convert each "thing" in the list to the proper thing by using ConvertAll and passing to him some converter.

I don't like this solution, it feels wrong because i create a list and create a new one. very inefficient. is there a better way to do it ?

thanks

Upvotes: 0

Views: 298

Answers (2)

user240141
user240141

Reputation:

try this quick and dirty. Not actual ,might contains error, you can use it as a reference.

Create a base class of thing having all common attributes

abstract ThingBase
{
   protected abstract   int Id {get;set;}
   protected abstract   string Name {get;set;}
}

Implement that base to your four things classes

public Thing1 :ThingBase
{
   public int Id {get;set;}
   public string Name {get;set;}
}
public Thing2 :ThingBase
{
   public int Id {get;set;}
   public string Name {get;set;}
}
public Thing3 :ThingBase
{
   public int Id {get;set;}
   public string Name {get;set;}
}
public Thing4 :ThingBase
{
   public int Id {get;set;}
   public string Name {get;set;}
}

Create one more helper class, that will contain the list of all 4 things

public class YourThings
{
    public IList<Thing1> thing1 {get;set;}
    public IList<Thing2> thing2 {get;set;}
    public IList<Thing3> thing3 {get;set;}
    public IList<Thing4> thing4 {get;set;}

}

Now Write 4 different Select Queries in your SP and catch it as a dataset in your datalayer. Extract the table and fill its respective list and return yourthing class to the UI layer.

public YourThings FunctionToReturnSingleYourThing()
{
}

of If You need a collection of YourThings , rebuild your logic and return like this

public List<YourThings> FunctionToReturnMultipleYourThings()
{
}

Upvotes: 1

Ivo
Ivo

Reputation: 8352

Why not use generics?

public IList<T> GetAllThings<T>(string tableName) where T : Thing {
    return new List<T>();
}

You will be able to call it

IList<Thing4> things4 = thingProvider.GetAllThing<Thing4>( "thing4Table" );

you could also have a Dictionary for storing the table name for each type, so you don't have to provide the table name to the method.

Upvotes: 5

Related Questions