Reputation: 1711
I know it sounds a bit weird, but I will try to explain it: suppose I have a class with a lot of properties, and all of them are read-only, so this class is the only one which can modify its properties (it is listening to an event, and fills the properties with the information contained on that event).
But, I want to encapsulate some of the properties on some structs, to create a well organized hierarchy, so these structs'properties should be read-only too, except for the owner class. For example:
public class A
{
private int a1;
public int A1
{
get{ return a1; }
}
private B structB;
public B StructB
{
get{ return structB; }
}
private method eventListenerMethod(...)
{
a1 = someValue;
structB.B1 = otherValue; //I want that only this class can modify this property!
}
}
public struct B
{
private int b1;
public int B1
{
get{ return b1; } // This property should be modifiable for Class A!!
}
}
I think I cannot do that, but does anyone know how can I achieve it? Thank you very much in advance.
Upvotes: 0
Views: 343
Reputation: 7609
Change the struct
to a class
and make it private
, but put the definition of it inside class A
.
This will mean only class A
has access to its properties. All the properties inside class B
can then be public (because only the class in which it's defined has access to it).
This will cause a compiler error because class B
will be private, but is exposed on a public property. To fix this, make a public interface to expose as the type IClassB
(bad name but you get the idea) and change the property type to be the interface. Ensure this interface has only get accessors on the property method signatures.
Something like this should work:
public class A : IClassB
{
public IClassB B { get; }
private class B : IClassB
{
public int B1 { get; }
}
}
public interface IClassB
{
int B1 { get; }
}
Upvotes: 0
Reputation: 782
Seems what you're after is the "friend" keyword in C++. However, it doesn't exist in C#, but "internal" is a good compromise. So, just make a "internal set" property, which'll be accessible (only) within the assembly. So other people who'll use your assembly won't have access to it
Upvotes: 1