Using the new INumber interface to determine if an object is a number without having the generic arg
With .net7 we now have the INumber<TSelf> interface which is pretty cool, and I thought I found a place where I might be able to use it for the first time. However, I am running into some trouble.
I am wondering if there is any way to know if some ‘object’ is a number and return the ‘One’ abstract static property from the INumber<TSelf> interface it would implement. The issue is I do not have a generic argument to plug in for TSelf, and I cannot add one in this case since the method I am working on is an override of a method outside of my control and it does not have a T generic argument.
Here is a cut-down example as a x-unit test of what I am doing and what I have tried.
Unfortunately, with INumber<TSelf> being so new there is not a lot of information about it online so before I give up, I figured I would see if anyone here knows how to achieve this.
6 Replies
According to 'https://stackoverflow.com/questions/73588532/access-abstract-interface-member-c11' these abstract members might only be accessible via their generic types. For example ‘T.One‘ rather than say ‘int.One’ or ‘INumber<int>.One’. This would tell me this is probably not possible, but I figured I would still see if anyone had anything.
Stack Overflow
Access Abstract Interface Member C#11
I'm trying to get the new AdditiveIdentity property from all of the inbuilt INumber<T> classes. So I'm starting with int (which should return 0).
However, I'm finding it difficult to actually...
You can't do this. You need the generic type (or reflection).
right, I guess what I was trying to figure out was how to do it with reflection, which I was unable to make work.
Maybe try having a generic method that you call with reflection which does the actual work
Excellent suggestion @vdvman1, Doing the following does in fact work for getting the ‘One’ abstract interface property from any of these number types. Very clever. Now I just need to figure out how to know if some Type is implementing the INumber interface before calling this.
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.