I have relativly often methods where i only want filled parameters as input. If somebody calls the method, and the parameters are not correct, an error should be thrown.
Is there a way to annotate a method to say: only certain value ranges are allowed, or they should be not null?
With generics there is something like the "where" clause for restrictions (whihc go not so far to have values).
So I want to do instead of
private static void DoSomething(string string_in, object object_in,... )
{
if (null == object_in) throw new NullReferenceException("Input parameter of object is empty.");
if (String.IsNullOrEmpty(string )) throw new NullReferenceException("Input parameter string is empty.");
something like
private static void DoSomething(string string_in, object object_in,... )
where string _in:!String.IsNullOrEmpty(string_in)
where object_in : object_in !=null
or
private static void DoSomething(string string_in != null, object object_in != null,... )
or (which i would like most)
[Restriction string_in: value != null, value != empty]
[Restriction object_in: value != null]
[Restriction int_in: value inRange 3..9]
private static void DoSomething(string string _in, object object_in,... )
So in short Is there a better way to restrict called type to a certain amount of values, then just do manually over and over again comparision to something?
Code contracts offer static analysis for your code, so it is quite close to what you need. As a bonus you can enable runtime checking also.
From msdn:
Code contracts provide a way to specify preconditions, postconditions, and object invariants in your code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits. Object invariants describe the expected state for a class that is in a good state.
Code contracts include classes for marking your code, a static analyzer for compile-time analysis, and a runtime analyzer. The classes for code contracts can be found in the System.Diagnostics.Contracts namespace.
The benefits of code contracts include the following:
Improved testing: Code contracts provide static contract verification, runtime checking, and documentation generation.
Automatic testing tools: You can use code contracts to generate more meaningful unit tests by filtering out meaningless test arguments that do not satisfy preconditions.
Static verification: The static checker can decide whether there are any contract violations without running the program. It checks for implicit contracts, such as null dereferences and array bounds, and explicit contracts.
Reference documentation: The documentation generator augments existing XML documentation files with contract information. There are also style sheets that can be used with Sandcastle so that the generated documentation pages have contract sections.