Q:

Overriding constants in derived classes in C#

In C# can a constant be overridden in a derived class? I have a group of classes that are all the same bar some constant values, so I'd like to create a base class that defines all the methods and then just set the relevant constants in the derived classes. Is this possible?
I'd rather not just pass in these values to each object's constructor as I would like the added type-safety of multiple classes (since it never makes sense for two objects with different constants to interact).

A:

It's not a constant if you want to override it ;). Try a virtual read-only property (or protected setter).
Read-only property:
public class MyClass {
    public virtual string MyConst { get { return "SOMETHING"; } }
}
...
public class MyDerived : MyClass {
    public override string MyConst { get { return "SOMETHINGELSE"; } }
}

Protected setter:
public class MyClass {
    public string MyConst { get; protected set; }

    public MyClass() {
        MyConst = "SOMETHING";
    }
}

public class MyDerived : MyClass {
    public MyDerived() {
        MyConst = "SOMETHING ELSE";
    }
}

A:

Unfortunately constants cannot be overridden as they are not virtual members.  Constant identifiers in your code are replaced with their literal values by the compiler at compile time.
I would suggest you try to use an abstract or virtual property for what you would like to do.  Those are virtual and as such can (must, in the case of an abstract property) be overridden in the derived type.

A:

Constants marked with const cannot be overridden as they are substituted by the compiler at compile time.
But regular static fields assigned to constant values can. I've had such a case just now:
class Columns
{
    public static int MaxFactCell = 7;
}

class Columns2 : Columns
{
    static Columns2()
    {
        MaxFactCell = 13;
    }
}

If I just redefined the MaxFactCell field in the derived class instead, polymorphism wouldn't work: code using Columns2 as Columns would not see the overriding value.
If you need to restrict write (but not read) access to the field, using readonly would prohibit redefining it in Columns2. Make it a property instead, that's slightly more code:
class Columns
{
    static Columns()
    {
        MaxFactCell = 7;
    }            
    public static int MaxFactCell { get; protected set; }
}

class Columns2 : Columns
{
    static Columns2()
    {
        MaxFactCell = 13;
    }
}

