How to cast an object (of type Object) into its real type?
I need to do some thing like this
Myobject [i] += Myobject [j];
Myobject’s type is Object.
Myobject [i] and myobject [j] will always be of same type.
Myobject[i].Gettype() would give me the type… but how would i actually cast the object into that type to perform the ‘+’ operator
I’m assuming the addition (
+) operator is defined for your custom type (MyTypein this example).If so, you simply need to cast the LHS and RHS of the assignment. This is required because both operands must be of known types at compile-time in order to choose the correct operator overload. This is something required by static languages, though dynamic languages (possibly C# 4.0) may resolve this.
Update:
Some reflection magic can get around this problem in C# 2.0/3.0 (with lack of dynamic typing).
Note that this only works for non-primitive types. For primitive types such as
int,float, etc., you would need to add a switch statement on the type that manually cast the operands and applied the addition operator. This is because operator overloads aren’t actually defined for primitive types, but rather built in to the CLR.Anyway, hope that solves your problem.