Reputation: 13
I'd like to know if this is possible
I have an assembly where there are two classes defined.
public class Foo
{
private Bar _Bar;
public Bar get { return _Bar ?? (_Bar = new Bar(this.Context)); }
}
internal class Bar
{
public void DoSomething() { }
}
And then a a separate 3rd party program that does something like this
public class SomeClass
{
public void ThisShouldWork()
{
Foo _Foo = new Foo();
_Foo.Bar.DoSomething();
}
public void ThisShouldNotWork()
{
Bar _Bar = new Bar();
Bar.DoSomething();
}
}
Is there a way that i can stop the instantiation of Bar classes, but allow them to be accessible via Foo?
The error in this example will be something along the lines of "property type Bar is less accessible than property Foo.Bar"
Upvotes: 0
Views: 58
Reputation:
There are two possible solutions here (possibly more?). The first is based on my comment:
Bar
has to be public, but its constructor doesn't.
public class Bar
{
internal Bar() { }
public void DoSomething() { }
}
With this, Bar
can only be constructed by classes within its parent assembly.
A second solution based on @Sinatr's comment:
Add public interface IBar to Bar and expose it instead.
public interface IBar
{
void DoSomething();
}
internal class Bar : IBar
{
public void DoSomething() { }
}
Then modify Foo
accordingly:
public class Foo
{
private IBar _Bar;
public IBar Bar { get { return _Bar ?? (_Bar = new Bar(this.Context)); } }
}
Upvotes: 4