Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent anyone from holding a reference to an object in C#

Tags:

c#

I have a class like this

internal class  Report
{
    public Company TargetCompany { get; private set; }

    .... // other stuff
}

I do not want any one to be able to do this

Report r = GetReport();

Company c = r.TargetCompany;

but instead always use

r.TargetCompany 

when they want access to the Company variable.

Is that possible? Does that even make sense?

like image 843
floatingfrisbee Avatar asked Jan 20 '26 01:01

floatingfrisbee


2 Answers

No, it's not possible.

And no, it really doesn't make sense either. Maybe if you explain your reasoning we'll understand a little better.

like image 160
Justin Niessner Avatar answered Jan 21 '26 13:01

Justin Niessner


No, that is not possible. The closest thing you can do is to provide wrappers to only allow access to the members within TargetCompany (not the company reference itself), or to return a copy of your internal TargetCompany member, preventing the internal one from being referenced (which has no real value).

like image 43
Reed Copsey Avatar answered Jan 21 '26 15:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!