❔ 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
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.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
eeeehhhh
dynamic
is generally very bad and is ill advised, but this might be a legitimate use-case for itYay, that realy seems to work 🙂
actually dynamic sounds usable
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
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.