Reputation: 326
Is there a way to ask that a method result respect a certain property? such as
interface MyInterface()
{
int MyMethod(int a, int b);
// i want that my int result is less then 10
}
I want to enforce in the definition this kind of request. Is it possible?
Upvotes: 1
Views: 61
Reputation: 6275
That is not possible using interfaces in c# unfortunately. You could have the caller of the interface enforce this or you use an abstract class instead:
abstract class MybaseClass()
{
protected virtual int MyMethodInternal(int a, int b){ //this method is not visible to the outside
// implementors override this
}
public sealed int MyMethod(int a, int b){ // users call this method
var res = MyMethodInternal(a,b);
if(res < 10)
throw new Exception("bad implementation!");
}
}
Upvotes: 2
Reputation: 11840
No, that's not possible. The contract simply doesn't define those kinds of constraints.
Interface constraints are checked at compile time, the return value of a function cannot in general be known by the compiler.
Upvotes: 0