4

Consider the following code:

int SomeField;
void Foo([Pure] Func<int, object> getData)
{
    Contract.Requires(getData != null);
    Contract.Requires(getData(this.SomeField) != null);
}

I get the following warning:

Detected call to method 'System.Func'2<System.Int32,System.Object>.Invoke(System.Int32)' without [Pure] in contracts of method '....Foo(System.Func'2<System.Int32,System.Object>)'

This warning makes perfect sense. But I'd still like to call the delegate in contracts and not get a warning (suppose I had warnings turned into errors). How do I achieve that?

I tried the attribute Pure, as shown in the example, but that doesn't work.

I'd also like to know why the PureAttribute can be specified on parameters. It wouldn't make sense if the type of the parameter wasn't a delegate type, and even if it is, it doesn't work as I'd expect, as I stated above.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
JBSnorro
  • 6,048
  • 3
  • 41
  • 62

2 Answers2

1

I'm not accustomed to the contracts framework, but from a purely logical way a delegate can't be pure, simply because it can take any method fulfilling the signature. There is no way you can guarentee that for all methods fitting that delegate, as it only requires one to break the contract.

Femaref
  • 60,705
  • 7
  • 138
  • 176
  • Ok. That makes sence too. Obviously not all delegates are Pure. That doesn't mean some can't be, and I think there should me a mechanism to specify that. But this raised a second question... I'll edit my post. – JBSnorro Feb 13 '11 at 22:37
1

The way to do this with the current Code Contracts library is to declare your own delegate type, like this:

[Pure]
public delegate U PureFunc<in T, out U>(T thing);

I think that the reason it doesn't work on delegate parameters is that it would be very hard to check in general :)

porges
  • 30,133
  • 4
  • 83
  • 114
  • Ok, that is a solution, although not very elegant, since that would require casting of delegates in other parts of the code, but ok, it's acceptable. But the thing is, when the PureAttribute is assigned to a method or delegate, it isn't checked for pureness, it is just assumed. So why can't I specify a delegate-parameter to be Pure? – JBSnorro Feb 14 '11 at 11:29
  • I think the difference is between *declaring* something to be pure and *requiring* it to be. When you declare a method Pure that's an active choice, but implicitly assuming delegates are Pure just because the parameter is isn't very ideal. In that case, the user of the method might not even know that the parameter is Pure, and might pass in something that will break. This way, the user of the method is required to say "yes, I know this has to be pure". – porges Feb 14 '11 at 20:18