Type T, object, & List<T>
I have a method that receives an object parameter. In some instances, the actual type is a List of unknown type.
I need to cast the parameter to a List and process the list items. I got close using Type.IsGenericType and GetGenericArguments().
Does anyone know how to do this?
Sam HobbsPosted Nov 21, 2009, 6:33 PM
What I would do is to put a line such as:
Type t = p.GetType();
in my program then set a breakpoint on that line or the line after it. Then I would look at the Type. I think you will see that the type name is something such as List`1 but I am notsure what the `1 is. There is other data, such as the namespace name, that might help.
As I say, I am not sure what you need to do. Something else that migh help is (assuming that o is the object that might be a List):
Cody SkidmorePosted Nov 21, 2009, 1:38 PM
Well, yeah. I know I've got it all wrong. :-) But that one line of code doesn't explain how to get the items out of the list and into a List
There must be a way to getting items out of the parameter or a cast I don't know about.
I actually tried casting/creating a List
Roei BarPosted Nov 21, 2009, 1:09 PM
create a list
and then run the foreach loop on this Objects List.
Cody SkidmorePosted Nov 21, 2009, 11:59 AM
protected string GetParameterValue(object value)
{
if (value.GetType().IsGenericType)
{
Type listItemType = value.GetType().GetGenericArguments()[0];
/// listItemType is a class (In this case, a LINQ entity)
/// that doesn't extend object. Then the cast fails.
}
if (value.GetType().IsGenericType)
{
StringBuilder sb = new StringBuilder();
List
for(Int32 i = 0; i < values.Count - 1; i++)
sb.Append(values[i].ToString());
return sb.ToString();
}
else
return value.ToString();
}
I tried variations of the following sytax before starting this post but can't get it working:
Type listItemType = value.GetType().GetGenericArguments()[0];
List
foreach(listItemType item in list)
{
/// process the item..
}
Roei BarPosted Nov 21, 2009, 3:16 AM
if its a Base T List like this List
meaning like this
List
and Product is all kind of objects that inherit from it. and then you can know exactly what T is