views:

248

answers:

4

Hi all, 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!

+3  A: 

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.

Nick Berardi
Chris
the compiler does a replace with literal values at compile time
Joe Pitz
`static` and `const` are better thought of as Global definitions, meaning that they don't abide by polymorphism. And can be called with out instantiating the class. Given that I have updated my post. You can do what you want, but you cannot really use polymorphism to accomplish it.
Nick Berardi
@Joe Pitz: The compiler will not replace a property with a literal at compile time. Especially for overriden properties, because of the base type it could be any number of values that inherit from the base type.
Nick Berardi
@Nick, consts are replaced at compile time: Here is a quote from Mircosoft::In fact, when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces. "http://msdn.microsoft.com/en-us/library/ms173119.aspx
Joe Pitz
+1  A: 

check out this prior post

You cannot override a const

http://stackoverflow.com/questions/770437/overriding-constants-in-derived-classes-in-c/770443#770443

Joe Pitz
+4  A: 

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"; } }
Pierre-Alain Vigeant
A: 

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.

boomhauer