How to have abstract and overriding constants in C#?
My code below won't compile. What am i doing wrong? I'm basically trying to have a public constant that is overridden in the base class.
public abstract class MyBaseClass
{
public abstract const string bank = "???";
}
public class SomeBankClass : MyBaseClass
{
public override const string bank = "Some Bank";
}
Thanks as always for being so helpful!
If your constant is describing your object, then it should be a property. A constant, by its name, should not change and was designed to be unaffected by polymorphism. The same apply for static variable.
You can create an abstract property (or virtual if you want a default value) in your base class:
public abstract string Bank { get; }
Then override with:
public override string Bank { get { return "Some bank"; } }
What you are trying to do cannot be done. static
and const
cannot be overridden. Only instance properties and methods can be overridden.
You can turn that bank
field in to a property and market it as abstract like the following:
public abstract string Bank { get; }
Then you will override it in your inherited class like you have been doing
public override string Bank { get { return "Charter One"; } }
Hope this helps you. On the flip side you can also do
public const string Bank = "???";
and then on the inherited class
public const string Bank = "Charter One";
Since static
and const
operate outside of polymorphism they don't need to be overriden.
In case you want to keep using "const", a slight modificaiton to the above:
public abstract string Bank { get; }
Then override with:
private const string bank = "Some Bank";
public override string Bank { get { return bank;} }
And the property will then return your "const" from the derived type.