3

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
  • Given which answer directed you to the solution, you should have shown quite a bit more code. If we had actually seen your code, it would have been clear. Commented Jun 25, 2009 at 2:12
  • That's why I asked for the error message :) Commented Jun 25, 2009 at 2:34

5 Answers 5

4
public abstract class Class1 { protected const string Prefix = "dynfrm_"; } public class Class2 : Class1 { public void GetConst() { Console.WriteLine(Prefix); } } 
Sign up to request clarification or add additional context in comments.

Comments

3

Here you go...

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

2 Comments

MyBase is just base in c#. Besides, base.myConstFiled isn't working for me.
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.
2

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.

Comments

1

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?

1 Comment

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?
0

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

2 Comments

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.
I was trying to access using this.Field.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.