Christian Madsen
Christian Madsen

Reputation: 1748

Generic only allowing only integers as type argument

I am writing a RationalNumber class in C# and would like to make it generic, but only allowing integers (int, byte, UInt32, my own BigInt class ...) as inputs - it doesn't make sense to have a rational number based on floats or even regular objects like Control.

However, it doesn't seem that I can filter out non-integer types when declaring the class.

Did I overlook something?

Upvotes: 3

Views: 154

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108810

No you can't.

And you have the additional problem that there is no arithmetic constraint either. So there is no statically typed way to use the operators of your type argument either. So you'll need to use dynamic which is slower (unless they improved the runtime/jitter since .net 3.5).

Some projects with similar problems didn't make the class generic at all, and used a code generator to specialize it instead.

Upvotes: 2

Related Questions