6

I have a List<dynamic> and I need to pass the values and type of the list to a service. The service code would be something like this:

 Type type = typeof(IList<>);
 // Type genericType = how to get type of list. Such as List<**string**>, List<**dynamic**>, List<**CustomClass**>
 // Then I convert data value of list to specified type.
 IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], genericType);

_dataSourceValues: values in the list

How can I cast the type of the list to a particular type if the type of List is dynamic (List<dynamic>)?

Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36
Steve Lam
  • 979
  • 1
  • 17
  • 40
  • [Does this answer help?](http://stackoverflow.com/a/557349/61470) –  May 14 '14 at 11:35
  • 1
    If you don't know the type in compile time you can't.(unless you use reflection) – Sriram Sakthivel May 14 '14 at 11:50
  • You can't cast it to a statically typed object, even using reflection. – Mike Goodwin May 14 '14 at 12:06
  • @MikeGoodwin Do you know why the OP wants to cast it? when you have a dynamic object I don't see why you would need to cast it. Isn't the main reason of having dynamic, escaping from the strong typing issues? Also, why do you think Reflection wouldn't help? – Farhad Alizadeh Noori May 14 '14 at 17:16

2 Answers2

1

If I understand you properly you have a List<dynamic> and you want to create a List with the appropriate runtime type of the dynamic object?

Would something like this help:

private void x(List<dynamic> dynamicList)
{
    Type typeInArgument = dynamicList.GetType().GenericTypeArguments[0];
    Type newGenericType = typeof(List<>).MakeGenericType(typeInArgument);
    IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], newGenericType);
}

On another note, I think you should rethink the design of your code. I don't really have enough context but I'm curious as to why you are using dynamic here. Having a List<dynamic> basically means you don't care what the type of the incoming list is. If you really care for the type(seems like you do as you are doing serialization) maybe you shouldn't be using dynamic.

Farhad Alizadeh Noori
  • 2,276
  • 17
  • 22
  • Thank for your responding. I figure out, dynamic is a object type (when I use get type method). About the rethink code: I have service to render report, so I need to pass all resources to it, in string, and that's why I use the above code. I cannot say clearly because job's requirement. – Steve Lam May 15 '14 at 07:50
1
 private void x(List<dynamic> dynamicList)
            {
                Type typeInArgument = dynamicList.GetType();
                Type newGenericType = typeof(List<>).MakeGenericType(typeInArgument);
                IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], newGenericType);
            }
Rashedul.Rubel
  • 3,446
  • 25
  • 36