C # Const field in abstract class

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

change

I had to clarify. My problem is that my child classes cannot see the const field:

protected const string Prefix = "dynfrm_";

If I remove the const keyword, I can jump to it from the grandson class.

+3
source share
5 answers

While you initialize it in the declaration, there should be no problems. What error message do you get?

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

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

...

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

, :

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

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

Visual Studio 2008 SP1, const IntelliSense , .

+2

, , ? , , .

Edit: I see that you posted the example - and indicated it as protected, which works for me. Got a description of what's going on? Not compiling? runtime error?

+1
source

Source: https://habr.com/ru/post/1711225/


All Articles