Sorry about replying almost a year too late :P
I recently used Java nested classes in an interesting way, and wanted to see if it can be done in C#.
In Java, the inner class AND the outer class can access private members of each other, which makes total sense as the classes are very closely related. They are in the same code file and are probably developed by the same developer. This allows the creation of inner classes that are immutable to external classes but can be modified by the outer class.
However, in C#, outer classes cannot access private members of inner classes so that concept is not directly applicable. I used an explicit interface as a workaround by defining a private interface in the outer class and explicitly implementing it in the inner class. This way, only the outer class can access the methods in this interface the same way it is done in Java (but they have to be methods, no fields).
Example:
public class Class1
{
public Class1()
{
Class2 c2 = new Class2();
// can modify field2
((I2)c2).field2 = 2;
}
private interface I2
{
// define the setter in the private interface
int field2 { set; }
}
public class Class2 : I2
{
// explicitly implement the setter
int I2.field2 { set; }
// create a public getter
public int field2 { get; }
}
}
class Class3
{
public Class3()
{
Class1.Class2 c2 = new Class1.Class2();
// can only read field2 because only the getter is public
// and I2 is private to Class1
int val = c2.field2;
}
}
That is what I would use explicit interfaces for. Any other suggestions?