• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 714
  • Last Modified:

dynamic casting for generic types

hello,

I need to make a cast to IList<T> but I will not know what T is until runtime.  Anyone know the best way to accomplish this... codeDOM perhaps?

Ultimately, I need to execute a statement like the following:

MethodInfo info;
Object obj;
IList<T> res = (IList<T>)info.Invoke(obj, new object[] { });

where:
the cast type will be info.ReturnType;  i.e. info.ReturnType == IList<T>
or T will be info.ReturnParameter.ParameterType;  i.e.  info.ReturnType.ParameterType == T

Does this make sense?

Thanks,
Robert

0
neudeal
Asked:
neudeal
  • 2
1 Solution
 
surajgupthaCommented:
Let me understand. you are looking to pass an array of strings to a function that should return you a List of type T , probably having the strings you sent as one of its properties ???
0
 
neudealAuthor Commented:
The method invoked by the MethodInfo instance described here will return an IList<> of some type T.  T could be strings, or foos or bars...  it will be an IList<> of whatever the MethodInfo.ReturnParameter is.

I guess the question is...  is there a way for me to declare and assign an instance of IList<T> while learning what T is on the fly?

Thanks,
0
 
surajgupthaCommented:
Kind of pseudo code, let me know if you need more specific code
                IList listObject = (IList)_dataSource;
                Type objectType = listObject[0].GetType();
                Type genericType = typeof(List<>);
                Type[] typeArgs = new Type[] { objectType };
                Type actualType = genericType.MakeGenericType(typeArgs);
                System.Reflection.ConstructorInfo constructorInfo = actualType.GetConstructor(new Type[] { });
                System.Collections.IList returnList = constructorInfo.Invoke(null) as System.Collections.IList;
                System.Reflection.PropertyInfo valueInfo = objectType.GetProperty(ValueMember);
0
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now