Victor Chekalin
Victor Chekalin

Reputation: 776

Cast to generic interface dynamically

I have an external function which has following syntax:

public void Set<FieldType>(
    Field field,
FieldType value
) 

Field type can be some of primitive types like int, double, bool etc. and also can be generic list of these types, e.g. IList< int >

The problem is that I must pass exactly an IList< T > interface. If I pass any type which implements IList< T > interface the function throws InvalidOperationException Unsupported type: System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

For example:

IList<int> list1 = new List<int>();
List<int> list2 = new List<int>();

Entity entity = new Entity();

//this works fine
entity.Set(field, list1);

//Here exception is throw
entity.Set(field, list2);

//works fine as well
entity.Set(field, list2 as IList<int>);

The issue that I get the list dynamically via reflection

var property = entityType.GetProperty(field.FieldName);
dynamic propertyValue = property.GetValue(myObject, null);

So, the propertyValue is List< T >, not a IList< T >, and when I pass this value to the external functions I see an exception.

Obviously, it is a bug of external function.

The only idea I have is to cast the propertyValue to IList< T >. But I don't know T at the compile time.

So, I need to cast dynamically. I've got a generic list interface type like variable

var genericIListType = typeof (IList<>)
    .MakeGenericType(field.ValueType);

But I cannot find the way how to cast propertyValue to this type. I can find only examples how to cast object to other objects (e.g. using Activator.CreateInstance), but I need to cast to an interface.

Please give me advice how to achieve the goal.

Upvotes: 2

Views: 647

Answers (1)

David M
David M

Reputation: 72860

You could wrap the external function:

public void SetWrapper<T>(Field field, List<T> list) {
    entity.Set(field, (IList<T>)list);
}

Upvotes: 5

Related Questions