Reputation: 21025
I want to know if there is any pattern that can overcome this problem: I have a set of properties that needed to be public to several classes and to other classes they should be only readonly, the classes must be public.
I do not want to use reflection or any other bad performance makers.
I know I can make them RO and implement logic inside class but I don't think it's good.
Any help?
Upvotes: 2
Views: 176
Reputation:
You could try declaring your setters as protected in your base class. Any class that derives it will be able to set it. But any class using the derived class will only see a read-only property.
public class ClassBase
{
public int MyProperty
{
get;
protected set;
}
}
public sealed class ClassDerived : ClassBase
{
public ClassDerived()
{
MyProperty = 4; // will set
}
}
public class ClassUsingDerived
{
public ClassUsingDerived()
{
ClassDerived drv = new ClassDerived();
drv.MyProperty = 5; // will fail
}
}
That is if i understand the question correctly :)
Upvotes: 0
Reputation: 21740
class Person : IReadOnlyPerson {
public string Name { get; set; }
}
public interface IReadOnlyPerson {
string Name { get; }
}
To those classes that should do r/o access - use IReadOlyPerson
Upvotes: 7
Reputation: 1063338
Inside the current assembly, you can make it internal
.
Outside the current assembly, the best you can do is make it available to specific assemblies, via [InternalsVisibleTo]
.
.NET does not offer more granular "friend" access.
Upvotes: 8
Reputation: 35741
Two options:
Sadly, there are no friend
classes in C#.
Upvotes: 2