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.