ctulu
ctulu

Reputation: 444

Prevent class's users to use setters

I'm trying to implement a simple sprite animating framework with C#. I have classes that have getters and setters. It's OK for me that using this getters and setters but the user of this framework should not see and use this setters. How can I achieve that?

Upvotes: 1

Views: 125

Answers (2)

lzcd
lzcd

Reputation: 1353

I'm a big fan of using explicit interfaces for this sort of situation... but "internal" will obviously do the job if the framework is contained within a single assembly.

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Check out the internal accessibility modifier, similar to public or private, but allowing access to the modified properties only to code compiled as part of the same assembly. You can specify it on the setter only, just like using private.

public string MyProperty {get; internal set;}

Of course, this isn't perfect. If your own framework is comprised of several assemblies, they would run into accessibility problems too. One option is to structure your solution accordingly. Another is to use the InternalsVisibleTo attribute, which lets an assembly explicitly name an external assembly as a "friend", allowing it access to its internal members.

Upvotes: 10

Related Questions