Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent property setter from modifying private property data

Tags:

c#

oop

Let me explain my question by posing a hypothetical situation. Lets start with a class:

public class PaymentDetails
{
    public int Id {get;set;}
    public string Status {get;set;}
}

And then I have another class:

public class PaymentHelper
{
    private PaymentDetails _paymentDetails;
    public PaymentDetails MyPaymentDetails{ get { return _paymentDetails; } }

    public PaymentHelper()
    {
        _paymentDetails = new PaymentDetails(); 
    }

    public void ModifyPaymentDetails(string someString)
    {
        // code to take the arguments and modify this._paymentDetails
    }
}

OK, so I have these two classes. PaymentHelper has made the property MyPaymentDetails read-only.

So I cannot instantiate PaymentHelper and modify MyPaymentDetails like this:

PaymentHelper ph = new PaymentHelper();
ph.MyPaymentDetails = new PaymentDetails(); // Not allowed!!! 

But I can modify the public properties inside of ph.MyPaymentDetails like this:

ph.MyPaymentDetails.Status = "Some status"; // This is allowed

How do I prevent that from working? Or is there no good way of doing that?

like image 744
quakkels Avatar asked Feb 09 '12 15:02

quakkels


1 Answers

A property may apply access modifiers to individual accessors, for instance:

public string Status { get; private set; }

The scope of access is left to your circumstance. Keeping it private, I'm sure you can tell, will mean only elements within the scope of the current class can use the setter, protected would allow inheritors to use it, etc.

Obviously your classes need to be engineered properly from the bottom up, so as to account for appropriate scoping and robust management when used further up the hierarchy.

like image 180
Grant Thomas Avatar answered Sep 24 '22 02:09

Grant Thomas