4

I am writing code contracts on an interface that uses events:

interface EventInterface<T> {
    event EventHandler ItemAdded;
    bool Add(T item);
}

When an item is added to a collection that implements the interface, the collection must raise an ItemAdded event. The event must only be raised if the item is added; this is given by the return value (think of a set, where true means the item was added, false means it wasn't added because it already existed in the set).

I wish to have a contract that ensures that if the result is true, an event will be raised. And likewise, if the result is false, no event is raised. Is there a way to check that using contracts?

Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44
  • 3
    You cannot "throw" an event. "Raised" is correct, you already used it, you should replace all instances of "throw" with it. – nvoigt Jan 04 '16 at 12:57

1 Answers1

1

That's not what code contracts are designed for. With an interface contract you can only specify details regarding parameters and return value of interface methods.

You may want to write an abstract base class that contains the event logic, or you could set up some unit tests for that.

Franz Wimmer
  • 1,477
  • 3
  • 20
  • 38
  • 1
    To second that, Code Contracts are a way of making guarantees to callers that if callers meet the stated preconditions, then they can expect the stated postconditions (if any) and object invariants (if any) to hold. Any other "internal" behavior of your objects (e.g. raising events) would be solely your responsibility, and as Franz says, something that can be easily ensured by performing unit and/or integration tests. Furthermore, Code Contracts _are not_ a replacement for software tests. The tools are complementary and testing is always required to ensure the quality of your software. – fourpastmidnight Feb 23 '16 at 21:28