What is the protected member point in System.Object?

A protected member is available within its class and instances of the derived class.

If each .NET type is derived from Object, is there any difference between the protected member and the public member in System.Object?

+6
source share
3 answers

As you said, a protected member is available within its class and any inheriting classes. An open member is accessible from any other class.

I see two protected Object elements in the MSDN documentation: Finalize and MemberwiseClone . These methods can be called within any inheriting classes (i.e., any class), but are not publicly available. If we have the following:

 class Foo { object Test() { return this.MemberwiseClone(); // Works, because Foo can see protected MemberwiseClone // inherited from Object } } class Bar { object Test() { var foo = new Foo(); return foo.MemberwiseClone(); // fails: Bar cannot see Foo protected MemberwiseClone // because Bar does not inherit from Foo } } 
+5
source

Yes

Just because you can access your "copy" of a protected member does not mean that you can access another type of copy. The following code will work with the β€œpublic” modifier.

The placement point of the protected member in Object (assuming you were able) was to make all objects have this element without exposing it to each other.

To prove this, I wrote this code (this will not compile):

 class BaseClass { protected bool sharedMember; } class DerivedClassA : BaseClass { public DerivedClassA() { DerivedClassB otherObject = new DerivedClassB(); otherObject.sharedMember = sharedMember; //Compiler error, cannot access protected member } } class DerivedClassB : BaseClass { } 
+2
source

Yes. There is a difference!

For example, say that you want each object in your application to save its creation time. You want all inheritors of Object to be able to read their OWN creation time, but you DO NOT want other objects to be able to read the creation time of their peers.

You can provide this encapsulation protected.

Each subclass, no matter how far down the chain, can access its creation time using the expression: this.timeOfCreation. Other objects will not be able to access, someOtherObject.timeOfcreation.

But, if you make timeOfCreation public, then ALL objects can read the creation time of other objects simply through the expression: someOtherObject.timeOfCreation. Now the creation time is not encapsulated / hidden at all!

So protected is always useful if you want to store sensitive information in an instance of a class and all its children. Publishing is useful if you don't care who can see the information inside the class. (for example, if you do not want data privacy)

0
source

Source: https://habr.com/ru/post/970352/


All Articles