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!
You can't do that. Show activity on this post. If a constant has a variable value, it's not a constant anymore. Static fields and methods are not polymorphic.
Abstract class members marked as abstract must be implemented by derived classes. An abstract class is a special type of class that cannot be instantiated and acts as a base class for other classes. Abstract class members marked as abstract must be implemented by derived classes.
If a method of a class is private, you cannot access it outside the current class, not even from the child classes of it. But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use. Therefore, the abstract method cannot be private.
An Abstract class can have access modifiers like private, protected, and internal with class members. But abstract members cannot have a private access modifier. An Abstract class can have instance variables (like constants and fields). An abstract class can have constructors and destructors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With