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
Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Return Value: This method returns the specified object after casting in the form of an object.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
I'm assuming the addition (+
) operator is defined for your custom type (MyType
in 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.
((MyType)Myobject[i]) += (MyType)Myobject[j];
Update:
Some reflection magic can get around this problem in C# 2.0/3.0 (with lack of dynamic typing).
public static object Add(object a, object b)
{
var type = a.GetType();
if (type != b.GetType())
throw new ArgumentException("Operands are not of the same type.");
var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public);
return op.Invoke(null, new object[] { a, b });
}
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.
Is the type known at compile time?
C# does not (until C# 4.0) support operators on anything except known, fixed types.
You can use operators with generics via a few tricks - like so. Let me know if generics are a factor here (I can talk at length on this...)
In 4.0, you can use:
dynamic x = MyObject[i];
x += MyObject[j];
MyObject[i] = x;
The use of dynamic
causes a lot of magic to happen ;-p
Other than those two scenarios, you need to know their type at compile-time, or do a lot of work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With