Is there a C# generic constraint for "real number" types?

c#, constraints, generics

Solution

You can't define such a constraint, but you could check the type at runtime. That won't help you for doing calculations though.

If you want to do calculations, something like this would be an option:

class Calculations<T, S> where S: Calculator<T>, new()
{
    Calculator<T> _calculator = new S();

    public T Square(T a)
    {
        return _calculator.Multiply(a, a);
    }

}

abstract class Calculator<T>
{
    public abstract T Multiply(T a, T b);
}

class IntCalculator : Calculator<int>
{
    public override int Multiply(int a, int b)
    {
        return a * b;
    }
}

Likewise, define a `FloatCalculator` and any operations you need. It's not particularly fast, though faster than the C# 4.0 `dynamic` construct.

var calc = new Calculations<int, IntCalculator>();
var result = calc.Square(10);

A side-effect is that you will only be able to instantiate `Calculator` if the type you pass to it has a matching `Calculator<T>` implementation, so you don't have to do runtime type checking.

This is basically what Hejlsberg was referring to in this interview where the issue is discussed. Personally I would still like to see some kind of base type :)

Problem

Possible Duplicate: C# generic constraint for only integers Greets! I'm attempting to set up a Cartesian coordinate system in C#, but I don't want to restrict myself to any one numerical type for my coordinate values. Sometimes they could be integers, and other times they could be rational numbers, depending on context. This screams "generic class" to me, but I'm stumped as to how to constrict the type to both integrals and floating points. I can't seem to find a class that covers any concept of real numbers... ``` public class Point<T> where T : [SomeClassThatIncludesBothIntsandFloats?] { T myX, myY; public Point(T x, T y) { myX = x; myY = y; } } Point<int> pInt = new Point<int>(5, -10); Point<float> pFloat = new Point<float>(3.14159, -0.2357); ``` If I want this level of freedom, am I electing for a "typeof(T)" nightmare when it comes to calculations inside my classes, weeding out bools, strings, objects, etc? Or worse, am I electing to make a class for each type of number I want to work with, each with the same internal math formulae? Any help would be appreciated. Thanks!

Original source

Related problems