Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I support Co-/Contravariance for Pub-/Sub-Scenarios in C#3.0?
    text
    copied!<p>In my application I am creating a simple event hub that offers something for registering subscribers:</p> <pre><code>Subscribes&lt;EventType&gt;(ISubscriber&lt;EventType&gt; subscriber) // and some other methods for adding subscribers </code></pre> <p>And for publishing events.</p> <pre><code>Publish&lt;EventType&gt;(EventType @event) </code></pre> <p>Quite simple. I want to route <code>Publish&lt;int&gt;(0)</code> to all subscribers implementing <code>ISubscriber&lt;int&gt;</code>.</p> <p>What's not too hard is, that I want the subscribers EventType to be contravariant. So <code>ISubscriber&lt;object&gt;</code> should basically consume everything. Not shure wether I want them to consume valuetypes, too.</p> <p>With C#4 that is no problem, but now I'm doing this stuff with C#3 and just faking contravariance with an interface:</p> <pre><code>public interface IContravariantGenerics { object AsVariantFor(Type[] genericParamters); } </code></pre> <p>Well, now, I want to empack data into "event types" like this. The generic parameters of that events must be covariant.</p> <pre><code>SubX : ISubscriber&lt;DataChanged&lt;A&gt;&gt; DataChanged&lt;T&gt; T Data {get;} </code></pre> <p>When I publish <code>Publish&lt;DataChanged&lt;B&gt;&gt;(new DataChanged&lt;B&gt;(new B())</code> (given B : A), the Subscriber should be notified with <code>DataChanged&lt;A&gt;</code> where Data is the B-instance passed to <code>DataChanged&lt;B&gt;</code>. So I need covariance support as well.</p> <p>I thought of writing a lib that supports both Co-/And Contravariance like this:</p> <pre><code>IMyObject&lt;T1, T2&gt; : IWithVariance&lt;In, Out&gt; </code></pre> <p>Which would allow conversions (not casts!) like this:</p> <pre><code>Obj&lt;Fruit, Fruit&gt; x; IMyObject&lt;Apple, object&gt; x2 = x.ToVariant&lt;Apple, object&gt;(); </code></pre> <p>What do you think? Is it possible? Thought of doing it using dynamic proxies.</p>
 

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