Mal Ross
Mal Ross

Reputation: 4701

Ranged integers in .NET (or C#)

Am I being blind, or does the .NET framework not provide any kind of ranged integer class? That is, a type that would prevent you setting a value outside some given bounds that are not the full range of the basic data type. For example, an integer type that would restrict its values to between 1 and 100. Showing my age here, but back in '93, I remember using that sort of thing in Modula-2 (eeek!), but I've not seen explicit framework / language support for it since.

Am I just missing something, or is it a case of "it's so simple to make your own that the framework doesn't bother"?

Cheers.

Upvotes: 3

Views: 519

Answers (3)

48klocs
48klocs

Reputation: 6103

They're not baked in like Eiffel's design by contract, but you can roll your own. For C# 3.5 and earlier, there's Spec#.

For C# 4.0, they've introduced CodeContracts (but it seems to be in BCL extensions).

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

You’re not missing anything – unless enums fit your case1) – it doesn’t exist. Roll your own.


1) And notice that enums actually don’t enforce a valid enum value because that would preclude of using enums for combined flags.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

There isn't a built-in class to support this, but typically, it's very easy to enforce in a property setter that it's normally not considered necessary.

Without properties, this would be much more useful. However, since you can do:

private int myRangedIntValue;
public int MyRangedIntValue
{
    get { return myRangedIntValue; }
    set 
    { 
        myRangedIntValue = Math.Max(1, Math.Min(100, value));
    }
}

The advantages of a custom type diminish. By leaving the standard int types, you have that many fewer types to worry about for compilation, data binding, etc.

Upvotes: 1

Related Questions