Just wondering if private class-level variables inherited? In C#
7 Answers
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But yes they really are

- 6,937
- 11
- 49
- 66
They are inherited, but the keyword "private" means that only the class in which they were declared can access them. This excludes subclasses. However, because an instance of a subclass contains its own superclass, they are still there. You just can't see them directly.
If are looking for a field that only the declaring class and its subclasses can see, you might use the keyword "protected" instead of "private", and that should provide the functionality you are looking for.

- 763
- 6
- 16
They are inherited in one sense. Memory space is allocated for them, and they "exist" within the subclass instance. However, the subclass can not access the variable itself. (If you want the subclass to access the base class variable, use protected
instead of private
.)
This is required - methods within the base class need to be able to set the private variable (or there'd be no use for it). Those methods are available on an instance of the subclass as well - and in fact, the subclass instance should be able to be treated as an instance of the base class (required to satisfy the Liskov substitution principle). If the private variables were not inherited, the behavior of the base class methods would change or break.

- 554,122
- 78
- 1,158
- 1,373
They are, though they are not directly accessible.
public class BaseClass
{
private const int _aNumber = 5;
public int ReturnANumber() { return _aNumber; }
}
public class DClass : BaseClass
{
public void SomeMethod()
{
// This is indirectly accessing a private implemented in the class
// this derives from, but existing inside this class.
int numbery = this.ReturnANumber();
}
}
public class Whatever
{
public void AMethod(DClass someDClass)
{
int thisIsNumberFive = someDClass.ReturnANumber();
}
}

- 5,909
- 30
- 53
It depends on language, but in general, no - they're only accessible in the class in which they're defined.

- 19,079
- 3
- 51
- 79
-
But they are usually part of the instance (even if the language prevents access). – Brian Rasmussen Jul 30 '10 at 17:05
They are inherited but not accessible or they are accessible only in the class where they are declared. You can access them in sub class by two ways
Declare them protected rather then private
write a public method which return the value of that private variable
but there is no way that you directly access private variable in subclass.
Yes, they are inherited but the compiler prohibits accessing them. Aalas, you still can get them -not recommended- through reflection or through your nice AMethod() trick.

- 1,164
- 9
- 10