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 ??
}
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.
}
}
You can access it from within a method. Try this:
class Espresso : Beverage
{
public void Test()
{
this.description = "sd";
}
}