1

In Delphi (or any Pascal) you can declare sub-range type so if you try assign value from outside allowed range, you would get compiler error.

var
    i: 1..8;
begin
    i := 8; // i := 9 would not work

Can this be done in C#? I can imagine creating custom struct, something like SubrangeType<byte> but I'm looking for something builtin.

EDIT: xanatos's and DavidHeffernan's comments gave me idea for more specific question. Subrange checking in Delphi is available both in run-time and compile-time. Implementing that on run-time would be possible in C# using custom struct but would it be possible to implement that checking on compile-time in C#?

Pol
  • 5,064
  • 4
  • 32
  • 51
  • Are the subranges separate types (so your i can "receive" the value from an int) or are simply compile-time checks? – xanatos Aug 18 '13 at 17:26
  • @xanatos- yes you can "receive" int value. this is compile-time support (not only check but also you can have for example a for loop which automatically will iterate only from 1 to 8) silly example but to give you idea. – Pol Aug 18 '13 at 17:30
  • @xanatos There is both compile time and runtime checking. The runtime checking is optional and is, obviously, for scenarios such as you describe where the compiler cannot verify correctness. – David Heffernan Aug 18 '13 at 17:40
  • @DavidHeffernan - yes, with $R directive on this can be checked in runtime as well. – Pol Aug 18 '13 at 18:49
  • I don't see how your edit changes anything. Without language support for integral types of user-specified range, you cannot hope for help at compile time. – David Heffernan Aug 18 '13 at 20:23
  • 1
    @jeroen This question asks "is there an equivalent in C#", but that question asks "why is there no equivalent in Java, C# and C++" – David Heffernan Aug 18 '13 at 20:39

1 Answers1

5

C# has no built-in language feature that is equivalent to Pascal subranges.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490