If I have a class (class P) which makes use of some other re-usable component (class C) (eg a state manager), then if that component needs to access some data within my top level class (P), then what choices do I have?
The key thing is that I dont want to expose this data to the outside world, just to within components I know and trust and use within P.
public static class Program
{
private void Main()
{
var owner = new Owner();
// I can call Foo()!!!
((IOwner)owner).Foo();
}
}
public interface IOwner
{
void Foo();
}
public class Owner : IOwner
{
private Component m_component;
public void SomeExternalAPI()
{
m_component = new Component(this);
m_component.DoSomething();
}
void IOwner.Foo()
{
// do something
}
}
public class Component
{
private readonly IOwner m_owner;
public Component(IOwner owner)
{
m_owner = owner;
}
public void DoSomething()
{
m_owner.Foo();
}
}
I could use an interface on P, but this then exposes the data externally. I could use an explicit interface on P, but this can be cast and so also easily exposes the data.
If I could somehow impart "Friendship" upon the component (which I created, and ideally at the instance level!), and make IOwner a friend-only interface then, it would be secure.
I know this is impossible in C# at the moment.
It comes up quite often for me.
Has anyone got any solutions or suggestions?