Why have class-level access modifiers instead of object-level?

While using C#, I recently realised that I can call a Foo object's private functions from Foo's static functions, and even from other Foo objects. After everything I have learned about access modifiers, this sounds very strange to me.

As far as I know, you make a function private when it does something that's part of some kind of internal process. Only the object itself knows when to use those functions, because other objects shouldn't/can't control the object's flow. Is there any reason why other objects of the same class should be excepted from this pretty straightforward rule?

As per request, an example:

public class AClass {
    private void doSomething() { /* Do something here */ }
    public void aFunction() {
        AClass f = new AClass();
        f.doSomething(); // I would have expected this line to cause an access error.
    }
}

Answers


When you make a member private, it's private to other classes not the class itself.

It can be useful for instance if you have an Equals method which needs access to another instance's private members:

public class AClass
{
    private int privateMemberA;

    // This version of Equals has been simplified
    // for the purpose of exemplifying my point, it shouldn't be copied as is
    public override bool Equals(object obj)
    {
        var otherInstance = obj as AClass;
        if (otherInstance == null)
        {
            return null;
        }

        return otherInstance.privateMemberA == this.privateMemberA;
    }
}

Need Your Help

Append text to form input element value on focusout()

jquery forms input

I'd like to append a 'saved' text to a value in an input form element when it goes out of focus. I've tried the following, but it doesn't seem to work.

Updating Database from ASP.NET

c# asp.net data-entry

I have a simple problem, and one I feel should be almost trivial. I have a set of data stored in a Database, and I'm using LinqToSql to read that data. That part is fine.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.