tags:

views:

1011

answers:

5

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.

+2  A: 

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.

Dustin Campbell
+3  A: 

Here you go...

  abstract class MyBase
    {
        protected const int X = 10;
    }
    class Derived : MyBase
    {
        Derived()
        {
            Console.WriteLine(MyBase.X);
        }
    }
Gishu
MyBase is just base in c#. Besides, base.myConstFiled isn't working for me.
Ronnie Overby
base is a c# keyword for the base class of the current class. MyBase is what Gishu declared as the abstract class in his sample code.
Timothy Carter
Oh I see. Thanks.
Ronnie Overby
@yshuditelu - Thank you for clarifying that bit
Gishu
A: 

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

KevDog
Error message? That's brilliant! "cannot be accessed with an instance reference; qualify it with a type name instead." I did this and it works. I guess it treats it as static when you use the const keyword.
Ronnie Overby
I was trying to access using this.Field.
Ronnie Overby
+1  A: 

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?

Tetraneutron
If a class is defined as abstact then it can never be initialized. Wouldn't this stop the compiler from initializing a const, which is inherently static? 
Brownman98
+2  A: 
public abstract class Class1
        {
            protected const string Prefix = "dynfrm_";
        }

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