1

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?

Davide Lettieri
  • 326
  • 2
  • 13

2 Answers2

2

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!");
    }
}
aL3891
  • 6,205
  • 3
  • 33
  • 37
  • Your first sentence may suggest that in some other languages it's possible to do what i need. Is it true? can you point me in some direction? – Davide Lettieri Oct 15 '13 at 08:21
  • You can look at [spec#](http://research.microsoft.com/en-us/projects/specsharp/) but I don't think it supports pre/post conditions on interfaces, only regular methods – aL3891 Oct 15 '13 at 18:04
0

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.

Baldrick
  • 11,712
  • 2
  • 31
  • 35