Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>In C# can you set constraints on events?</p> </blockquote> <p>Nope.</p> <blockquote> <p>I want to limit the types that can subscribe to a particular event based on the interface they implement.</p> </blockquote> <p>Event listeners are <em>instances of delegates of a type compatible with the event type</em>. "Types" are not listeners of events.</p> <blockquote> <p>I.e. I want an object "Employee" implementing IPerson to subscribe to an event handler but another object "Truck" implementing a totally different interface to be restricted. </p> </blockquote> <p>An "employee" object doesn't listen to an event in the first place. The only thing that listens to an event is a <em>delegate object</em>. </p> <p>Are you saying that you only want to accept delegates that are delegates to methods that happen to be instance methods of a particular class? That is a very strange thing to do and <strong>I recommend that you not attempt to do so</strong>. </p> <p>It is not possible to prevent that <em>at compile time</em>, but if you are really hell-bent on doing this strange thing, you can do it at runtime. </p> <p>To do so, as the other answers note, you can create adder and remover accessor methods for the event, and then put a check in the adder that verifies that the receiver of the delegate is of a type you approve of, and throw an exception if it is not. </p> <p>But again, this sounds like an extraordinarily bad idea. It is up to the listener to decide whether or not they are interested in the event, not up to the event source to vet its listeners. Users have the reasonable expectation that any accessible event can be listened to by any delegate of a compatible type.</p> <p>Perhaps you can explain why you want to do this strange thing; there might be a better way to achieve your aim.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload