How to have abstract and overriding constants in C#?

C#PolymorphismConstants

C# Problem Overview


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!

C# Solutions


Solution 1 - C#

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"; } }

Solution 2 - C#

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.

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - C#Pierre-Alain VigeantView Answer on Stackoverflow
Solution 2 - C#Nick BerardiView Answer on Stackoverflow
Solution 3 - C#Brady MoritzView Answer on Stackoverflow