Tony_Henrich
Tony_Henrich

Reputation: 44085

Restricting read/write access of class properties to certain classes in .NET

Is there a good way to allow only a certain class to have read/write access to properties in another class without having inheritance structure between them during design mode in .NET?

So if a class has public properties, only a certain class has visibility to these properties?

If not possible during design mode, then during run time. I know of a hokey way using flags in set and get statements but I think there are better ways.

Upvotes: 3

Views: 1410

Answers (3)

Talljoe
Talljoe

Reputation: 14827

If you make the properties public anyone can access them. If you make them internal, protected, or even private --- anyone can still access them using reflection. If you want to discourage their use, use internal like Mitch suggested.

If there is a security reason for having this constraint, use Code Access Security to protect your properties. Note that this isn't something simple you can throw together -- thought must be put into your security model and the permissions you expose. Also realize that this must be done on an assembly level and will affect deployment of your application.

Chances are you probably don't need to do something so deep. You can probably "discourage" people from accessing those properties by hiding them behind an explicitly-implemented interface.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062560

There is no friend access in C#. You have public/protected/internal (including [InternalsVisibleTo]), but nothing more granular (i.e. at the inter-type level). So, no.

Upvotes: 4

Mitch Wheat
Mitch Wheat

Reputation: 300519

You can implement this using the internal keyword in C#:

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly, as in this example:

public class BaseClass 
{
    // Only accessible within the same assembly
    internal static int x = 0;
}

See also: Practical usings of “internal” keyword in C#

Upvotes: 2

Related Questions