C# Type Casting at Runtimefor Array.SetValue
Posted
by
sprocketonline
on Stack Overflow
See other posts from Stack Overflow
or by sprocketonline
Published on 2010-12-31T20:36:07Z
Indexed on
2010/12/31
20:53 UTC
Read the original article
Hit count: 209
I'm trying to create an array using reflection, and insert values into it. I'm trying to do this for many different types so would like a createAndFillArray
function capable of this :
Type t1 = typeof(A);
Type t2 = typeof(B);
double exampleA = 22.5;
int exampleB = 43;
Array arrA = createAndFillArray(t1, exampleA);
Array arrB = createAndFillArray(t2, exampleB);
private Array createAndFillArray(Type t, object val){
Array arr = Array.CreateInstance( t, 1); //length 1 in this example only, real-world is of variable length.
arr.SetValue( val, 0 ); //this causes the following error: "System.InvalidCastException : Object cannot be stored in an array of this type."
return arr;
}
with the class A being as follows:
public class A{
public A(){}
private double val;
public double Value{
get{ return val; }
set{ this.val = value; }
}
public static implicit operator A(double d){
A a = new A();
a.Value = d;
return a;
}
}
and class B being very similar, but with int
:
public class B{
public B(){}
private double val;
public double Value{
get{ return val; }
set{ this.val = value; }
}
public static implicit operator B(double d){
B b = new B();
b.Value = d;
return b;
}
}
I hoped that the implicit operator would have ensured that the double be converted to class A, or the int to class B, and the error avoided; but this is obviously not so.
The above is used in a custom deserialization class, which takes data from a custom data format and fills in the corresponding .Net object properties. I'm doing this via reflection and at runtime, so I think both are unavoidable. I'm targeting the C# 2.0 framework.
I've dozens, if not hundreds, of classes similar to A
and B
, so would prefer to find a solution which improved on the createAndFillArray
method rather than a solution which altered these classes.
© Stack Overflow or respective owner