I found something similar on another question but i couldnt solve my problem as i'm still quite new in c#.
i have
System.Type type; // for example int[]
System.Type elementType = type.GetElementType(); //for example int
and a List that i need to cast to int[]
object valueObj; //is my List<object> i want to cast to int[]
I'm trying the following:
MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast")
.MakeGenericMethod( new System.Type[]{ elementType } );
MethodInfo toArrayMethod = typeof(Enumerable).GetMethod("ToArray")
.MakeGenericMethod( new System.Type[]{ elementType } );
var castedObjectEnum = castMethod.Invoke(null, new object[] { valueObj });
var castedObject = toArrayMethod.Invoke(null, new object[] { castedObjectEnum });
in the last line i get this runtime exception
InvalidCastException: Cannot cast from source type to destination type.
System.Linq.Enumerable+c__Iterator01[System.Int32].MoveNext ()
System.Collections.Generic.List
1[System.Int32].AddEnumerable (IEnumerable`1 enumerable)
as a last thing i need to assign the casteObject to a privateField using
field.SetValue(this, castedObject);
Edit:
I will try and get more info on that but to better explain what i'm trying to do i will explain the use case.
i serialize to disk in json some class fields, and then when i deserialize i get back a List where i serialize a base array of int/bools/string
I'm doing the serialization and deserialization by marking fields with a custom attribute, and i want to be able to serialize both Array and Lists of any basic type
i will double check and get with more info