6

If I have ObjectA, and it has a private method GetPrice() and also has a "parent" field of the same type, why am I able to call GetPrice() on the parent instance from within the child instance?

Example:

private decimal GetPrice()
{
    ObjectA parent = Parent;

    if(parent != null)
    {
        return parent.GetPrice(); // Why is this OK?
    }

    return 0;
}
1
  • 1
    Because the language designers thought it should work that way? Commented Nov 2, 2012 at 13:12

3 Answers 3

14

Because private means "not accessible to other types", not "not accessible to other instances".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks...In the 5 years I've been programming C#, I never noticed this. I guess from the time I learned C#'s access modifiers, I mistook it as being private to the instance. Now I feel like a fool. Ya learn something every day!
@Ryan, I know what you mean... I guess this is one of those things you can "misunderstand" for a long time. And basically it behaves just like you'd think, until you actually try to access another instance's private member and realise that it's allowed :)
This is quite surprising to me. Is there any literature that describes why it is like this?
6

Because private scope is limited to the class, not the instance as defined in the C# spec:

1.6.2 Accessibility Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following table.

Accessibility       Meaning   

public              Access not limited   
protected           Access limited to this class or classes derived from this class  
internal            Access limited to this program   
protected internal  Access limited to this program or classes derived from this class    
private             Access limited to this class

Comments

1

An access modifier is related to it's implementing class/type not to instances of that class

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.