Why it's only permissible to use public member of the base class within a method not the class body?
You are thinking about this the wrong way.
It is not the accessibility rules that make this illegal; it would be illegal regardless of the accessibility.
The rule you are violating is that a statement must appear within the body of a method, property, constructor, destructor, indexer, operator or event. In your first code sample the statement appears outside of all of those, and in the second, it appears inside a method.
Again, this rule has nothing whatsoever to do with accessibility. It's a grammatical rule of the language that you are violating, not a semantic rule.
That should answer your question, but let's take a look at your code. The better way to write this would be:
abstract class Car
{
public abstract double MaximumSpeed { get; }
}
class Minivan : Car
{
public override double MaximumSpeed { get { return 100.0; } }
}
Why is this better?
- Public fields are a bad idea. Represent things that are logically properties as properties.
- The property is now read-only. You don't want just anyone to be able to change the value!
- Use good naming conventions.
- Car is abstract, so you cannot create a vehicle that is just a car.
- The maximum speed is a "physics" quantity, so it should be double, not int. There is no requirement that speed be quantized to an integer.