Inheriting Consts

  • Thread starter Thread starter Jon
  • Start date Start date
Am I missing something quite simple as I can't seem to see how to
inherit consts from my base class.

Can this be done?

What exactly do you mean? You should be able to refer to constants (so
long as they're accessible) from a derived class. For example:

using System;

class Base
{
public const int TestConstant = 10;
}

class Test : Base
{
static void Main()
{
Console.WriteLine (TestConstant);
}
}

Is your constant private by any chance? (This is the default if you
don't specify an access level.)

Jon
 
Jon said:
Am I missing something quite simple as I can't seem
to see how to inherit consts from my base class.

You can't override the value of a constant in a derived class, because
constants are static members.

Eq.
 
Paul,

then how do you solve in C# cases like (I do not draw the inheritence
lines, I hope it is obvious):

Class Vehicle with static constant: NumberOfWheels

Class Auto: NumberOfWheels = 4; Class Bycicle: NumberOfWheels = 2;
Class Amphibian: NumberOfWheels =0;

There should be only one NumberOfWheels in each class (because it is
common for all instances), but they should have different values.

Thank you,
Janos
 
then how do you solve in C# cases like (I do not draw the inheritence
lines, I hope it is obvious):

Class Vehicle with static constant: NumberOfWheels

Class Auto: NumberOfWheels = 4; Class Bycicle: NumberOfWheels = 2;
Class Amphibian: NumberOfWheels =0;

There should be only one NumberOfWheels in each class (because it is
common for all instances), but they should have different values.

The number of wheels should be related to an *instance*, with Vehicle
having a protected constructor taking the number of wheels. Auto would
always pass 4, Bicycle would always pass 2 etc.

It has to be instance data otherwise you can't ask an arbitrary
vehicle how many wheels it has.

An alternative if there are many similar values is to have flyweight
"VehicleKind" with Auto, Bicycle etc instead of using polymorphism -
each vehicle would have a VehicleKind which in turn would know how
many wheels it had etc.

Jon
 
Janos said:
then how do you solve in C# cases like [...]
Class Vehicle with static constant: NumberOfWheels
Class Auto: NumberOfWheels = 4;
Class Bycicle: NumberOfWheels = 2;

abstract class Vehicle
{
public abstract int NumberOfWheels { get; }
}

class Auto : Vehicle
{
private const int WHEELS = 4;
public override int NumberOfWheels { get { return WHEELS; } }
}

Eq.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top