c# - Covariant interface with contravariant interface as member property -


i have interface defines reader , writer ifoo.

public interface ifoobarstore<out e>  e : class, ifoobar {     ifoobarreader<e> getreader();     ifoobarwriter<e> getwriter(); } 

ifoobarstore covariant. ifoobarstore interacts derived ifoo. such, more derived ifoo should assignable more derived ifoo type argument.

// derivedfoobitystore.cs public sealed class derivedfoobitystore  : ifoobarstore<myfoobity> {     // implementation follows } 

if ifoobarstore defined being variant ifoobarstore<e> instead of ifoobarstore<out e>, following produce compiler error cs0266.

ifoobarstore<ifoo> mygenericstore = new derivedfoobitystore(); 

the reader defined covariant well. should allow reading derived ifoo objects somewhere.

using system.collections.generic; public interface ifoobarreader<out e>  e : class, ifoo {     ienumerable<e> getall();     ienumerable<e> getby(params object[] vars);     e getsingle(object uniqueidentifier); } 

ifoobarwriter exposes members used standard crud operations on ifoo.

public interface ifoobarwriter<in e>  e : class, ifoo {     void add(e foo);     int delete(e foo);     e update(e foo); } 

since every operation has single argument of type e (any class derived ifoo), ifoobarwriter must flagged contravariant.

when compile code receive error:

invalid variance: type parameter 'e' must contravariantly valid on 'ifoobarstore<e>.getwriter()'. 'e' covariant.

how can better refactor code compiles successfully?

for moment got around refactoring ifoobarwriter work object instead of ifoo.

public interface ifoobarwriter<out e>  e : class, ifoo {     void add(object foo);     int delete(object foo);     object update(object foo); } 

this renders basic premise of ifoobarwriter obsolete.

the solution remove e acceptable argument instance member methods of ifoobarwriter.

public interface ifoobarwriter<out e>  e : class, ifoo {     void add(ifoo foo);     int delete(ifoo foo);     object update(ifoo foo); } 

by having add, delete, , update accept ifoo limit types can work on (as opposed setting argument object) enough business requirements.

having type parameter e ifoobarwriter remain covariant allows remain part of ifoobarstore interface.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -