Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerics, Inheritance and the new operator
    text
    copied!<p>Here is something that I find myself using from time to time and I just wanted to get some feedback on the merits of the practice.</p> <p>Lets say that I have a base class:</p> <pre><code>abstract class RealBase { protected RealBase(object arg) { Arg = arg; } public object Arg { get; private set; } public abstract void DoThatThingYouDo(); } </code></pre> <p>I often create a second base class that is generic that handles the cast from the "object" type in the base class to the "T" type, like this:</p> <pre><code>abstract class GenericBase&lt;T&gt; : RealBase { protected GenericBase(T arg) : base( arg ) { } new public T Arg { get { return (T) base.Arg; } } } </code></pre> <p>This allows me to access "Arg" as its explicit type without a cast operation: </p> <pre><code>class Concrete : GenericBase&lt;string&gt; { public Concrete( string arg ) : base( arg ) { } public override void DoThatThingYouDo() { // NOTE: Arg is type string. No cast necessary. char[] chars = Arg.ToLowerInvariant().ToCharArray(); // Blah( blah, blah ); // [...] } } </code></pre> <p>All the while being able to also work with it via the "RealBase":</p> <pre><code>class Usage { public void UseIt() { RealBase rb = new Concrete( "The String Arg" ); DoTheThing(rb); } private void DoTheThing(RealBase thingDoer) { rb.DoThatThingYouDo(); } } </code></pre> <p>It is assumed that there are many other "Concrete" types... not just the one.</p> <p>Here are my questions/concerns:</p> <ol> <li>Am I "off my rocker" for using an approach like this? </li> <li>Are there any obvious drawbacks/caveats to using this approach? </li> <li>What about that "new public T..." in GenericBase? Good/bad idea? Awkward?</li> </ol> <p>Any feedback or advice would be greatly appreciated.</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