Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following doubt.
Having a class which contains a bunch of members, one of which is an object of another class.
I am creating accessors to protect the input to non-object members (like, for instance, strings) , and I am wondering if it makes sense to do the same for the object member.

If i do something like this :

public class MyClass {

     string       member1;
     AnotherClass member2;

     string       Member1 {  get; set;}
     AnotherClass Member2 {  get { return member2;}
                             set {  ......do some controls....
                                    member2 = .... }

}


As far as I know (but I maybe wrong) , no matter what I do in the Member2.set method ,
if I use the Member2.get , I get a reference to the private member2 object, and with this , I could bypass the controls made in Member2.set accessor . Or is there some hidden control mechanism that prevents me from using the reference in such a way, once I have declared the member2 reference as private ?

What I have tried:

looked unsuccessfully into the site for an answer
Posted

1 solution

Nope, if you return the reference, it is the reference and the caller can do anything he likes with it.

If you want to restrict access to it's internals, you need to fully encapsulate it, and provide properties and / or methods to expose only those features you want teh caller to access.

And please, specify your access explicitly!
C#
public class MyClass {
 
     private string       member1;
     private AnotherClass member2;
 
     public string       Member1 {  get; set;}
     public AnotherClass Member2 {  get { return member2;}
                                    set {  ......do some controls....
                                          member2 = .... }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900