4

Wondering if there is a way to validate right on the input of the method? I realize I can easily do this later and throw an error but it would be nice if was caught compile time.

Instead of

CursorPosition(int x, int y)
{
 if (x >= 80) { Console.WriteLine("off screen"); }
 if (y >= 24) { Console.WriteLine("off screen"); }
}

Couldn't I just have it done here, and have the compiler throw back and error?

CursorPosition(int x < 80, y < 24)
{
 // do stuff
}

Thanks so much!

xmael91nt
  • 76
  • 3
  • 2
    You can, with Code Contracts. – Dai Sep 02 '17 at 03:26
  • Would you like to check condition when passing parameters without going to body? –  Sep 02 '17 at 03:39
  • Very similar question, though focused more on ensuring parameters are non-`null`: [A tool for automatically testing parameters of methods and throwing ArgumentNullException for .net/VS?](https://stackoverflow.com/q/5419408/150605) – Lance U. Matthews Sep 02 '17 at 03:52
  • Possible duplicate of [Restrict value of a parameter in a constructor AT DESIGN TIME](https://stackoverflow.com/questions/3327186/restrict-value-of-a-parameter-in-a-constructor-at-design-time) – Lance U. Matthews Sep 02 '17 at 03:54
  • You can write tests for your application/method, where you will check that `CursorPosition` method will never get "invalid" values. You can run tests on every build. – Fabio Sep 02 '17 at 03:59
  • The compiler, no. Short of actually running your program, how would it figure out whether `CursorPosition(row, col)` is valid for the arbitrary values held in the variables `row` and `col`? – paxdiablo Sep 02 '17 at 04:58
  • @paxdiablo: How? With an SMT solver and abstract interpretation! – Eric Lippert Sep 02 '17 at 16:08

1 Answers1

5

The feature you want is called dependent types -- so called because the type depends on a value. Dependent type systems can represent concepts like "a positive integer less than 80" or "a pair of integers where the first is the smaller", or "an integer and an array where the integer is less than the array length", and that sort of thing.

C# does not support dependent types directly. The closest you can get is, as noted in a comment, by annotating your program with code contracts. Code contracts give you the ability to both check your program statically to see if there are possible type violations, and to turn the contracts into check-and-throw at runtime.

There are a number of interesting languages which do support dependent types, but most of them are purely functional languages.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • Thank you very much for the comprehensive answer! For my project a console based input tool, it is pretty trivial to evaluate inside the method, however it seemed like something I should be able to do. I appreciate you give me the details. I google around looking at languages that support dependent types. It seems nearly none from what I can tell? – xmael91nt Sep 02 '17 at 16:00