× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

C# How to make a factory method return of the subclass type

James Jensen
Feb 10, 2015
<p>Make it recursively generic:</p> <pre><code>public class BankAccount&lt;T&gt; where T : BankAccount&lt;T&gt;, new() { public T SomeFactoryMethod() { return new T(); } } public class SavingsAccount: BankAccount&lt;SavingsAccount&gt;{} </code></pre> <p>You'll note that I made the factory method non-static, because static methods aren't inherited.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/24705030/C#%20How%20to%20make%20a%20factory%20method%20return%20of%20the%20subclass%20type/24705088">Stack Overflow</a>.</p>
comments powered by Disqus