|
|
|
|
|
by noblethrasher
4153 days ago
|
|
We've had a robust way of doing code contracts since C# 2.0. If you instruct the compiler to treat all warnings as errors (so that variables must be defintitely assigned), then the following code gives you what you want: public PositiveInt SomeMethod(GreaterThanFive a, NonNegative b)
{
//do stuff;
}
public struct GreaterThanFive
{
readonly int n;
public GreaterThanFive (int n)
{
if(n < 5)
throw new ArgumentException("n must be greater than 5")
this.n = n;
}
public static implicit operator GreaterThanFive(int n)
{
return GreaterThanFive(n);
}
public static implicit operator int (GreaterThanFive n)
{
return n.n;
}
}
//Similar definitions for NonNegative and PositiveInt
We can even have nice diagnostic messages since the advent of C# 5's CallerInfo attributes (CallerMemberName, CallerLineNumber, and CallerFilePath). |
|
It also might not be super amenable to static analysis.