Introduction
It is known that to control the accessibility level of a class member, we have to use one of the access modifiers (i.e. public, protected, internal, or private). However, there are times when it becomes desirable to have different classes with different access rights given to its class members. This article explains a method of doing this by using interfaces and adapter classes. This can be explained by the following scenario:
Let's assume that we have three classes: SharedClass, ClassA, and ClassB and we need an instance of SharedClass to be shared between ClassA and ClassB, but we want ClassA to have access to certain parts of SharedClass instance and ClassB to have access to the other part of the class. These requirements cannot be met by using the traditional access modifiers (i.e. public, protected, internal, or private). So, what is the solution? The solution lies in using interfaces.
Solution
Let's assume that SharedClass has two data members (DataA, DataB) and we want ClassA to control (i.e. to see) only DataAA and ClassB to control DataB. The following code shows the use of interfaces to meet these requirements:
public interface PartA
{
void SetDataA(string dataA);
string GetDataA();
}
public interface PartB
{
void SetDataB(string dataB);
string GetDataB();
} public class SharedClass:PartA,PartB
{
private string DataA;
private string DataB;
public void SetDataA(string dataA)
{
DataA=dataA;
}
public string GetDataA()
{
return DataA;
}
public void SetDataB(string dataB)
{
DataB=dataB;
}
public string GetDataB()
{
return DataB;
}
}public class ClassA
{
public PartA mSharedInstance;
public ClassA (PartA obj)
{
mSharedInstance =obj;
}
}
public class ClassB
{
public PartB mSharedInstance;
public ClassB (PartB obj)
{
mSharedInstance =obj;
}
}
Now, let's test the code.

As can be seen (Figure1), ClassA can only see certain parts of SharedClass. However, the use Interfaces is not limited to this. See the following code:
public interface PartA
{
void SetDataA(string dataA);
string GetDataA();
void DoTask();
void SharedTask();
}
public interface PartB
{
void SetDataB(string dataB);
string GetDataB();
void DoTask();
void SharedTask();
}
public class SharedClass :PartA,PartB
{
private string DataA;
private string DataB;
public void SetDataA(string dataA)
{
DataA=dataA;
}
public string GetDataA()
{
return DataA;
}
public void SetDataB(string dataB)
{
DataB=dataB;
}
public string GetDataB()
{
return DataB;
}
void PartA.DoTask()
{
}
void PartB.DoTask()
{
}
public void SharedTask()
{
}
}

As can be seen (Figure2), SharedClass has two methods that have the same name but they define different accessibilities. Moreover, SharedClass has got a shared method that can be accessed either by ClassA or ClassB.
Conclusion
Interfaces are used in C# not only for multiple inheritance but also to have well-defined and advanced accessibility levels to class members.