Question

I'm having trouble declaring a const field in an abstract class. Why is this?

edit

I should have clarified. My problem is that my child classes can't see the const field:

protected const string Prefix = "dynfrm_";

If I remove the const keyword, I can get to it from a grandchild class.

Was it helpful?

Solution

As long as you initialize it in the declaration, there shouldn't be an issue. What is the error message you are receiving?

OTHER TIPS

public abstract class Class1
{
    protected const string Prefix = "dynfrm_";
}

public class Class2 : Class1
{
    public void GetConst()
    {
        Console.WriteLine(Prefix);
    }
}

Here you go...

abstract class MyBase
{
    protected const int X = 10;
}
class Derived : MyBase
{
    Derived()
    {
        Console.WriteLine(MyBase.X);
    }
}

Seems to work fine:

public abstract class Class1
{
    protected const int Field1 = 1;
}

public class Class2 : Class1
{
    public int M1()
    {
        return Field1;
    }
}

I'm using Visual Studio 2008 SP1, and I see the protected const in IntelliSense from a descendant and it compiles as expected.

Did you make your constant at least protected? if it's private it won't be accessible by child classes just as it wouldn't if it wasn't an abstract class.

Edit: I see you posted an example - and did specify it as protected, which works for me. Got a description of what happens? Doesn't compile? run time error?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top