Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a generic typed member variable without type parameters specified on the class
    primarykey
    data
    text
    <p>I apologise for the unclear title, I don't really know how else to say it. I'll demonstrate with code. </p> <pre><code>public class CalculationService { private static Calculator&lt;StaticInstrument, StaticResult&gt; _staticCalculator; private static Calculator&lt;DynamicInstrument, DynamicResult&gt; _dynamicCalculator; private static readonly object IsInitializedLock = new object(); public byte[] ProcessStatic() { lock (IsInitializedLock) { _staticCalculator = new Calculator&lt;StaticInstrument, StaticResult&gt;(); } return _staticCalculator.Calculate(); } public byte[] ProcessDynamic() { lock (IsInitializedLock) { _dynamicCalculator = new Calculator&lt;DynamicInstrument, DynamicResult&gt;(); } return _dynamicCalculator.Calculate(); } } </code></pre> <p>I have many methods that are identical, except for the fact that the type parameters of the Calculator objects are different.</p> <p>The problem is, because <code>CalculationService</code> is a WCF service, it <em>cannot</em> have any type parameters. For this reason I can't simply create a static member <code>Calculator&lt;TInstrument, TResult&gt;</code>, because I cannot put type parameters on <code>CalculationService</code>.</p> <p>My <em>ideal</em> solution would be something like this:</p> <pre><code>public class CalculationService { private static Calculator&lt;TInstrument, TResult&gt; _calculator; private static readonly object IsInitializedLock = new object(); public byte[] Process&lt;TInstrument, TResult&gt;() { lock (IsInitializedLock) { _calculator = new Calculator&lt;TInstrument, TResult&gt;(); } return _calculator.Calculate(); } public byte[] ProcessStatic() { return Process&lt;StaticInstrument, StaticResult&gt;(); } public byte[] ProcessDynamic() { return Process&lt;DynamicInstrument, DynamicResult&gt;(); } } </code></pre> <p>But I can't create that <code>private static Calculator&lt;TInstrument, TResult&gt; _calculator</code> member without specifying type information on <code>CalculationService</code>, which I cannot do with WCF.</p> <p>The only way I can think to do this would be to have</p> <pre><code>private static dynamic _calculator; </code></pre> <p>Is there any other way? I would rather avoid using dynamic if possible, I'm not sure what the performance implications could be, if any.</p>
    singulars
    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.
 

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