How to choose between private and protected access modifier to encapsulate members between base and childs classes?

Why don’t I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?

When you call a public method on a class, that method can access private members of that class:

public class Foo
{
    public void Bar()
    {
        Baz();
    }

    private void Baz()
    {
        // private method called by public method
    }
}   

var foo = new Foo();
foo.Bar();

This compiles just fine. Your setter is the same: it’s public, so callable from everywhere, even if it accesses private members.

As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.

You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you’re just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:

public long ID { get; set; } = -1;

Then you can access the property everywhere, from within itself, from derived classes and from code using this class.

See also:

Leave a Comment