Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle static fields that vary by implementing class
    primarykey
    data
    text
    <p>I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).</p> <ol> <li>I define an interface ICommand</li> <li>I create an abstract base class CommandBase which implements ICommand, to contain common code.</li> <li>I create several implementation classes, each extending the base class (and by extension the interface).</li> </ol> <p>Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...</p> <p>For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:</p> <p>public abstract static const string Name;</p> <p>However (sadly) you cannot define static members in an interface.</p> <p>I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.</p> <hr> <p>UPDATE:</p> <ol> <li>I can't get the code formatting to work properly (Safari/Mac?). Apologies.</li> <li><p>The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).</p></li> <li><p>I forgot to mention - ideally I want to be able to query this information statically:</p> <p>string name = CommandHelp.Name;</p></li> </ol> <p>2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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