Private class with Public method?

Sandy picture Sandy · Oct 15, 2011 · Viewed 15.6k times · Source

Here is a piece of code:

private class myClass
{
   public static void Main()
   {

   }
}

        'or'

private class myClass
{
   public void method()
   {

   }
}

I know, first one will not work. And second one will.

But why first is not working? Is there any specific reason for it?

Actually looking for a solution in this perspective, thats why made it bold. Sorry

Answer

Richard Ev picture Richard Ev · Oct 15, 2011

It would be meaningful in this scenario; you have a public class SomeClass, inside which you want to encapsulate some functionality that is only relevant to SomeClass. You could do this by declaring a private class (SomePrivateClass in my example) within SomeClass, as shown below.

public class SomeClass
{
    private class SomePrivateClass
    {
        public void DoSomething()
        {

        }
    }

    // Only SomeClass has access to SomePrivateClass,
    // and can access its public methods, properties etc
}

This holds true regardless of whether SomePrivateClass is static, or contains public static methods.

I would call this a nested class, and it is explored in another StackOverflow thread.