Reputation: 3
For example if I have Class1
and Class2
but I only want Class3
to have access to them, how would I go about setting this up?
I was looking into multiple inheritance, but it doesn't seem like it's possible in C#. I would like for my presentation layer to only call Class3
and Class3
will either call Class1
or Class2
based on a property set in the constructor of Class3
.
Class1()
{
object GetData()
{
}
}
Class2()
{
object GetData()
{
}
}
public Class3()
{
bool mForClass2 = false;
Class1 mClass1;
Class2 mClass2;
public Class3(bool forClass2)
{
mForClass2 = forClass2;
mClass1 = New Class1();
mClass2 = New Class2();
}
public object getdata()
{
if(mForClass2)
{
return mClass2.getdata();
}
else
{
return mClass1.getdata();
}
}
}
Upvotes: 0
Views: 111
Reputation: 9648
This is exactly what private inner classes are designed to do.
public class Class3
{
public enum Type { Order, Inventory }
private interface IProvidesGetData{ object getData(); }
private class Class1 : IProvidesGetData { /* ... */ }
private class Class2 : IProvidesGetData { /* ... */ }
//...
}
Upvotes: 3
Reputation: 127543
To extend off of what clcto answered, you don't need to all be in a single file. You can split it up by using partial classes
//In Class3.cs
public partial class Class3
{
public enum Type { Order, Inventory }
//...
}
//In IProvidedsGetData.cs
partial class Class3
{
private interface IProvidesGetData
{
object getData();
}
}
//In Class1.cs
partial class Class3
{
private class Class1 : IProvidesGetData
{
/* ... */
}
}
//in Class2.cs
partial class Class3
{
private class Class2 : IProvidesGetData
{
/* ... */
}
}
Upvotes: 1
Reputation: 44439
Make both Class1
and Class2
internal
and put them together with public Class3
in the same package.
This will restrict visibility of the first two to that package (essentially: Class3
) and class3
is still publicly available.
Ofcourse, don't add any [InternalsVisibleTo]
stuff.
As others have noted you can also use several different private
classes, but that will give you one big source file: not handy to work with. Using this method you can split it up over multiple files.
Following your comment, you could have a setup like this:
public enum CrudAction {
Add, Update, Get
}
public class UIController {
public void Perform(CrudAction action) {
switch(action){
case CrudAction.Add: new AddAction().Perform(); break;
case CrudAction.Get: new GetAction().Perform(); break;
case CrudAction.Update: new UpdateAction().Perform(); break;
default: throw new ArgumentException();
}
}
}
internal interface IAction {
void Perform();
}
internal class AddAction : IAction { }
internal class GetAction : IAction { }
internal class UpdateAction : IAction { }
Now everything is split over multiple files and you can only access it using
new UIController().Perform(CrudAction.Update);
Upvotes: 0