Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Determine the type of a generic list

I have a C# method that I need to pass various lists into. The type of lists will be different very often. The method itself is in a different dll and cannot know the class objects contained in the lists (no references, no using statements). The method needs to read each of the members of each of the items in a list and build and return a string based off of that.

My question is how can get the metadata for for these various objects at compiletime / runtime? Will reflection do that?

Also, once I get the metadata, how do i use it to actually use the variables?

Thank you

EDIT: currently I am using it like the following:

public string GetData(List<User> list){
//...
    List<RowData> rows = new List<RowData>();
    foreach (User item in list)
    {
        RowData row = new RowData();
        row.id = count++;
        row.cell = new string[3];
        row.cell[0] = item.ID.ToString();
        row.cell[1] = item.name;
        row.cell[2] = item.age.ToString();

        rows.Add(row);
     }
//...
    return new JavaScriptSerializer().Serialize(rows.ToArray());

Right now this is very specific. I want to replace this with generics so I can pass items other than "User"

like image 406
Mike Avatar asked Jan 25 '26 04:01

Mike


1 Answers

If the parameter (will call it list for discussion's sake) coming into the method is List<T> then you can do the following:

Type type = list.GetType().GetGenericArguments()[0];

If you just have a generic T class, then you can always just go with this:

Type typeParameterType = typeof(T);
like image 73
Karl Anderson Avatar answered Jan 26 '26 18:01

Karl Anderson