Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my privates accessible?

Tags:

c#

.net

oop

I have the following code:

public class PersonInitializer
{
    private Person _person;

    public static Person LoadFromFile(string path)
    {
        PersonInitializer x = new PersonInitializer();

        Person p = x._person; //Why am I accessible?

        return x.LoadFromFile(); //Sure.

    }

    public Person LoadFromFile(string path)
    {

    }
}

Why is _person accessible from x even if it is private? What can I do to "protect" _person?

like image 888
Ian Avatar asked Dec 02 '22 03:12

Ian


2 Answers

It is accessible, because you are the class it is defined in!

Access modifiers apply to classes, not to instances of a class. That means, an instance of class A has access to all private members of another instance of class A.

I assume, you agree with me, that this is ok:

var p = this._person;

But what about this:

public void DoSomething(PersonInitializer personInitializer)
{
    var p = personInitializer._person;
}

According to your assumption, this code would be valid depending on the input.
Example:

DoSomething(this); // ok
DoSomething(other); // not ok

This makes no sense :-)

like image 126
Daniel Hilgarth Avatar answered Dec 14 '22 22:12

Daniel Hilgarth


This is because you are accessing it from a member function. If you want to prevent access from that particular function, you may want to move that static function to a new class.

like image 33
Shamim Hafiz - MSFT Avatar answered Dec 14 '22 23:12

Shamim Hafiz - MSFT