Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access protected variable in subclass?

I have an abstract class with a protected variable

abstract class Beverage
{
        protected string description;

}

I can't access it from a subclass. Intellisense doesn't show it accessible. Why is that so?

class Espresso:Beverage
{
    //this.description ??
}
like image 988
Ufuk Hacıoğulları Avatar asked Dec 21 '25 23:12

Ufuk Hacıoğulları


2 Answers

Short answer: description is a special type of variable called a "field". You may wish to read up on fields on MSDN.

Long answer: You must access the protected field in a constructor, method, property, etc. of the subclass.

class Subclass
{
    // These are field declarations. You can't say things like 'this.description = "foobar";' here.
    string foo;

    // Here is a method. You can access the protected field inside this method.
    private void DoSomething()
    {
        string bar = description;
    }
}

Inside a class declaration, you declare the members of the class. These may be fields, properties, methods, etc. These are not imperative statements to be executed. Unlike code inside a method, they simply tell the compiler what the members of the class are.

Inside certain class members, such as constructors, methods, and properties, is where you put your imperative code. Here is an example:

class Foo
{
    // Declaring fields. These just define the members of the class.
    string foo;
    int bar;

    // Declaring methods. The method declarations just define the members of the class, and the code inside them is only executed when the method is called.
    private void DoSomething()
    {
        // When you call DoSomething(), this code is executed.
    }
}
like image 54
Matthew Avatar answered Dec 24 '25 12:12

Matthew


You can access it from within a method. Try this:

class Espresso : Beverage
{
    public void Test()
    {
        this.description = "sd";
    }
}
like image 31
Teoman Soygul Avatar answered Dec 24 '25 13:12

Teoman Soygul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!