Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For one thing, accessing <code>Banana.Suppliers</code> is misleading. It will always yield the same result as accessing <code>Apple.Suppliers</code> etc - you've got a <em>single</em> collection of suppliers.</p> <p>Basically any time you access <code>Banana.Suppliers</code> the compiler emits a call to <code>Fruit.Suppliers</code>: that's why just calling <code>Banana.Suppliers</code> isn't triggering the static constructor which adds the banana supplier.</p> <p>The reason you only see the suppliers added in the static constructor for bananas after you've created a banana is that that forces the static constructor to run. You could do anything else that forced the static initializer to run, and you'd get the same results. One example would be calling a static method within <code>Banana</code> itself.</p> <p>Now, I strongly suspect that you've got a significant problem in that you'll be using the same suppliers for all types. Obviously this isn't your <em>real</em> code, and the best solution will depend on what you want your real code to do. Generics can give you effectively "per type" static variables using type arguments : <code>Foo&lt;Banana&gt;.StaticProperty</code> and <code>Foo&lt;Apple&gt;.StaticProperty</code> will really be different, assuming <code>StaticProperty</code> is declared in <code>Foo&lt;T&gt;</code>.</p> <p>EDIT: With regards to your edit, I would suggest avoiding using statics here. Possibly create a factory for each type (implementing an interface which may be generic). Note that you may well be able to avoid creating a separate factory <em>type</em> for each subtype, if you can create an appropriate instance with all the relevant items for each type.</p> <p>We'd really need to see more of an example to say for sure, but in general I find that the less static data you have, the more testable your design will be and the less you'll run into problems like this :)</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