I\'m looking an interval data type for .NET 4.0. For example the interval (a,b], all point x such that a What i would like to be able to do are create interv
EDIT 2019: As of C# 8.0/.NET Core 3.x/.NET Standard 2.1 there is now a System.Range that provides minimal interval functionality with endpoints. I'm leaving the rest of this answer as-is.
As others have stated, there are no integrated interval type. Depending on the needs of your project, a simple Tuple
Many implementations can be found online. There is the basic generic Range class part of the Microsoft Research Dynamic Data Display project and another from Kevin Gadd. The AForge project contains a non-generic IntInterval/DoubleInterval implementation. Other (1, 2) SO questions might also be of interest. Andy Clymer has an interesting dynamically compiled implementation on his blog. More complete solutions can be found on CodeProject, in Jon Skeet's book and From Russia with Love. There seems to be a few (1, 2) commercial solutions as well. I've seen others before that I can't find at the moment.
Whatever you do, please watch out when using a generic interval type. It's actually hard to write a correct monolithic generic interval class because integer and floating point intervals have different mathematical properties. For example all integer intervals can be represented with closed endpoints and the pair [1,2] [3,6]
can be considered as contiguous, equivalent to [1,6]
. None of this is true with floating points intervals. See Wikipedia for details. A group of classes might be better, with an abstract generic base class and typed derived classes IntInterval or DoubleInterval to implement the different behaviors.
Aside from the math, there are a few more implementation difficulties with generic interval types. It's not possible to easily do arithmetic with generics in C#, and there is floating point NaN and rounding errors to take care of. See the Boost library documentation for IntervalIComparable
.
As I mentioned before, the choice of what is appropriate in terms of functionality and correctness all depends on the requirements of your projects.