Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of a dynamic object in C#?

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>)?

like image 295
Steve Lam Avatar asked Oct 31 '22 23:10

Steve Lam


2 Answers

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.

like image 151
Farhad Alizadeh Noori Avatar answered Nov 15 '22 08:11

Farhad Alizadeh Noori


 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);
            }
like image 22
Rashedul.Rubel Avatar answered Nov 15 '22 08:11

Rashedul.Rubel