Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ranged integers in .NET (or C#)

Tags:

c#

.net

range

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.

like image 671
Mal Ross Avatar asked Jan 20 '26 18:01

Mal Ross


2 Answers

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).

like image 116
48klocs Avatar answered Jan 23 '26 09:01

48klocs


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.

like image 21
Konrad Rudolph Avatar answered Jan 23 '26 08:01

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!