I need something like Add(object arg0, object arg1)

Hi!

I have a baseclass MyBaseClass that has two methods:

virtual System.Type GetProvidedType()
virtual object GetProvidedData()

There are some implementations of that baseclass, and they all provide completely different data. Some may provide an int, some may provide a Vector2, or some complex type. I can’t say what at compile time.

What I would like to do, is adding the returns of two different GetProvidedData() calls.
Something like:

MyBaseClass provider0 = GetProvider(0);
MyBaseClass provider1 = GetProvider(1);
return provider0.GetProvidedData() + provider1.GetProvidedData();

That, of course, leads to error CS0019: Operator ‘+’ cannot be applied to operands of type ‘object’ and ‘object’.

  • I tried using the dynamic keyword. But that’s not implemented enough yet in Unity.
  • I tried using reflection. Like making GetProvidedData() a generic method, getting the MethodInfo via reflection, using MakeGenericMethod, and calling that. Which of course, when invoked, provides me with an effing object again.
  • Even Convert.ChangeType returns an object. Which, at that point, is useless to me.
  • I tried getting the + operator via reflection (it’s a method with the name “op_Addition”), but that won’t work for native types like int.

Any ideas how to tackle this?

Some may provide an int, some may provide a Vector2, or some complex type. I can’t say what at compile time…What I would like to do, is adding the returns of two different GetProvidedData() calls

But even if the methods returned a Vector2 and an int instead of object and object, you would still have the same basic problem. You’d have to define in some way what is the result of e.g. Vector2.zero + 3 and all the other possible combinations of data you might end up adding together.

Without exactly understanding the problem and requirements for the output, I would probably approach this by making some kind of a wrapper class that can store any of the data types you might be storing/adding and for example overriding the basic operators to produce whatever you need the result to be depending on the input types stored in the wrappers being added together.

In theory the principle is almost the same as just making a big if-else with all the possible combinations of objects cast to their actual types etc. but it would be a bit cleaner and maintainable this way. The root of the problem is that the C# language only defines the result of adding together certain types and all the rest you have to define yourself.