views:

106

answers:

5

I'm creating a list of <T>, but i want to know the type of that T-object. (i'm using reflection in my project, so i don't know the type when i'm creating my code.

So first i have my List --> List<T> values

Now i want to get all the properties of that T-object (for creating columns in a datagrid)

any help?

A: 

You can take one object from that list and look at its type. Though there is certainly a better way, I think.

Joey
What if not all the collection of the same type?
Ahmed Khalaf
@Ahmed - then it isn't a sensible list; actually, looking at the first item in the list is the official fallback approach used when an `IList` isn't also an `ITypedList`, and doesn't have a non-object indexer. So it isn't a *bad* suggestion. But if a `T` *can* be identified from the list itself, it is preferable.
Marc Gravell
The question clearly states it's a List<T>, there is no reason why the items in the list would be of different types
Abhijeet Patel
Well, the T might be a supertype of all items in the list, so you get a car for item 1, a bicycle for item 2, etc.
Joey
+11  A: 

You can just use typeof(T) in your class or generic method:

void ProcessList<T>(List<T> list) {
    Type typeOfT = typeof(T);
    // Work with type...
}
Reed Copsey
If the OP is using reflection (question), then there isn't a very good way of calling this method without already knowing the `T` in advance; at least, not until C# 4.0 (you could use it as a dynamic method and let the runtime worry about it).
Marc Gravell
A: 

Is it as easy as GetType(), and then using reflection for GetProperties()?

Jarrett Meyer
+1  A: 

For a GetListType function see this answer. To get the properties of the list for data-binding purposes, you should really use the component-model (for compatibility) - i.e.

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(type);

Then look at each PropertyDescriptor, using GetValue / Converter etc. Your list code will generally have to work against the non-generic IList; something like:

IList list = ...
object obj = list[rowIndex];
// then for any given "prop"
object val = prop.GetValue(obj);
string displayText = prop.Converter.ConvertToString(val);

However, if you wanted to be "complete" you'd also need to look at IListSource and ITypedList

Marc Gravell
A: 
 values.GetType().GetGenericArguments()[0].FullName

The above gives you the type object for type 'T'

values.GetType().GetGenericArguments()[0].GetProperties(System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance)

The above gives you the public properties available on 'T',you can pass in the appropriate BindingFlags as you see fit.

Abhijeet Patel