Just wondering if private class-level variables inherited? In C#

+6  A: 

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But yes they really are


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

But they are usually part of the instance (even if the language prevents access).
Brian Rasmussen
+7  A: 

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.

+1  A: 

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();
Jimmy Hoffa
+4  A: 

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.

Reed Copsey

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.

Edgar Sánchez

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

  1. Declare them protected rather then private
  2. 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.