In Java, if a nested class is not declared as static, it cannot be accessed within a static context. This means an instance of the inner class can only be created through an instance of the outer class. For example:
class Prac{
class Inner{}
public static void main(){
Inner myObj = new Prac().new Inner();
}
}
For my Java-adjusted brain, this makes sense. If an inner class isn't static, it would require an instance of the outer class to be instantiated from. In c# however, I can declare Inner non-statically as a nested class and directly instantiate it from a static context in the Main method.
I read that c# nested classes are like c and not java, but I'm not familiar with how inner classes work in any other way. What are the mechanics underlying nested classes in c#?
CodePudding user response:
Consider that Microsoft strongly suggests to avoid public nested classes. The core idea of a nested class is to completely hide to everyone an implementation detail of an abstraction. Consider that example:
IUserService
public interface IUserService
{
IEnumerable<string> GetAllUsernames();
}
MockUserServiceProvider
public static class MockUserServiceProvider
{
// Public
public static IUserService New() => new MockUserService();
// Nested Private class
private class MockUserService : IUserService
{
public IEnumerable<string> GetAllUsernames()
{
yield return "Bob";
yield return "Mary";
}
}
}
The goal of the Mock provider is to make available to the public an instance of the interface to Mock, it does not make sense to bind the provider to a specific class type, indeed, in theory, that type just shouldn't exist at all. So the best one can do (Without use some I.L. magic as Moq does for example) is to completely hide the class definition with a private nested class, so that no one can access it.
