Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn object as interface from generic method
    text
    copied!<p>I have one interface <code>InterfaceBase</code> and some interfaces derived from it <code>Interface1, Interface2</code>. Next I have classes that are implementing the <code>InterfaceX</code> interfaces, not the base one.</p> <p>Now, i am beginner in generics and so many new approaches in this made great mess in my head :( . I want to create factory (static class) where I call something like</p> <pre><code>Interface1 concrete1 = Factory.Get&lt;Interface1&gt;(); </code></pre> <p>Here is my (sample) implementation of factory, that does not work:</p> <pre><code> public static class Factory { public static T Get&lt;T&gt;() where T: InterfaceBase{ Type type = typeof(T); //return new Concrete1() as T; // type T cannot be used with the as //return new Concrete1() as type; //type not found //return new Concrete1(); // cannot implicitly convert //return new Concrete1() as InterfaceBase; //cannot convert IBase to T //return new Concrete1() as Interface1; //cannot convert Interface1 to T } } </code></pre> <p>What I want to achieve is hide the classes (they are webservice handlers) from the rest of the application to exchange them lightly. I wanted use the factory as the classes will be singletons and they will be stored in Dictionary inside the factory, so the factory can spread them across the application through this method, but as interfaces.. Maybe i am not using the constraints correctly am I doing smthing wrong? is my approach bad? can be there something better, maybe the whole architecture shoul be reworked? diagram to show better the <a href="http://i260.photobucket.com/albums/ii22/cccp14/other/newArch.png" rel="nofollow">architecture</a>. The factory is not in it</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