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

Is it possible to implement the "virtual constructor" pattern in C# without casts?

Asad Saeeduddin
Oct 08, 2015
<p>Here is a way to do this that doesn't involve any casting. It doesn't allow you to do <code>new Base()</code> from your first snippet, which doesn't make any sense because it is abstract, but the rest works:</p> <pre><code>interface Base { Base DeepClone(); } abstract class Base&lt;T&gt;: Base where T: Base&lt;T&gt; { public abstract T DeepClone(); Base Base.DeepClone() { return DeepClone(); } } class Base2 : Base&lt;Base2&gt; { public override Base2 DeepClone() { return new Base2(); } } </code></pre> <p>Then, in your <code>Main</code> method:</p> <pre><code>public static void Main() { var y = new Base2(); // Base2 overrides DeepClone Base b = y.DeepClone(); Base2 c = y.DeepClone(); // Compiles an works } </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30083354/Is%20it%20possible%20to%20implement%20the%20%22virtual%20constructor%22%20pattern%20in%20C#%20without%20casts?/30083844">Stack Overflow</a>.</p>
comments powered by Disqus