C
C#2y ago
IceReaper

❔ How to calculate with numbers which are typed as object?

I have a function which gets a List<object> parameter. Several different sources are actually adding a value to the list, which might be anything from byte to decimal. Basicaly any buildin number type. Im trying to calculate using the values in the list, one after another. However its not possible to simply to "a + b" if both are only known as "object". I could ofcourse do 15 * 15 type checks (possible number types) for a and b, just to be able to sum them and get the appropriete result (int + int = int, int + float = float, ...). Is there any better solution to this at all? Help would be very appreciated!
7 Replies
Thinker
Thinker2y ago
Not really, unfortunately. In .NET 7 there is the INumber<T> interface which allows you to use operations such as + on a generic type, although that requires statically knowing that type.
IceReaper
IceReaperOP2y ago
Yeah, that was my first idea, but it would only help to build Add(T a, T b) => a + b; basicaly. But i think i just stumbled across something which may work: dynamic keyword
Thinker
Thinker2y ago
eeeehhhh dynamic is generally very bad and is ill advised, but this might be a legitimate use-case for it
IceReaper
IceReaperOP2y ago
Yay, that realy seems to work 🙂
Binto86
Binto862y ago
actually dynamic sounds usable
Thinker
Thinker2y ago
One of the few unfortunate aspects of static abstracts in interfaces is that the interfaces only become usable through generics, so in cases like this you're just outta luck
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server