0

I am making a class, class numToBin <T>, and I need to make sure that T is a numeric value (Ex., Float, Double, Int, Long, UInt, Ulong, byte, short, BigInteger). I have seen a lot of posts asking the same question, but they are all a couple of years old.

My question is: Have there been any changes to the language to allow it now? Currently I have:

class numToBin <T>
    where T : struct, IEquatable<T>, IFormattable, IComparable, IComparable<T>

But something like T a = 0; doesn't work.

Sean Werkema
  • 5,810
  • 2
  • 38
  • 42
Optimistic Peach
  • 3,862
  • 2
  • 18
  • 29
  • "has there been any changes to the language to allow it now?" No. – spender Jun 14 '17 at 23:33
  • Could you link an answer or two that you think is out of date? – Sergey Kalinichenko Jun 14 '17 at 23:33
  • https://stackoverflow.com/questions/1267902/generics-where-t-is-a-number https://stackoverflow.com/questions/3329576/generic-constraint-to-match-numeric-types https://stackoverflow.com/questions/2645301/generics-that-restricts-the-types-to-int-double-long Just some examples... – Optimistic Peach Jun 15 '17 at 01:13
  • I updated the title of your question to more clearly describe what you were trying to do. I fixed the formatting, a few minor grammar and punctuation errors, and corrected your capitalization. I also turned the snippet of your existing code into a cleaner, neatly-indented, more-readable form. – Sean Werkema Jun 16 '17 at 13:08

2 Answers2

1

No, there is still no generic type constraint for a "numeric" type.

To get your T a = 0 specifically you can just use T a = default(T). The default of all numeric types is 0.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
0

In the constructor of your class, perform type inspection to match the applicable types. If it fails throw an InvalidCastException or InvalidArgumentException.

Type t = typeof(T);
bool good = (t == typeof(int)) || (t == typeof(long))|| //...
if(!good)
 //die
awiebe
  • 3,758
  • 4
  • 22
  • 33