Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private class with Public method?

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

like image 314
Sandy Avatar asked Oct 15 '11 10:10

Sandy


3 Answers

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.

like image 73
Richard Ev Avatar answered Nov 10 '22 13:11

Richard Ev


Richard Ev gave a use case of access inside a nested classes. Another use case for nested classes is private implementation of a public interface:

public class MySpecialCollection<T> : IEnumerable<T>
{ 
    public IEnumerator<T> GetEnumerator()
    {
        return new MySpecialEnumerator(...);
    }

    private class MySpecialEnumerator : IEnumerator<T>
    {
        public bool MoveNext() { ... }
        public T Current
        { 
            get { return ...; }
        }
        // etc...
    } 
}

This allows one to provide a private (or protected or internal) implementation of a public interface or base class. The consumer need not know nor care about the concrete implementation. This can also be done without nested classes by having the MySpecialEnumerator class be internal, as you cannot have non-nested private classes.

The BCL uses non-public implementations extensively. For example, objects returned by LINQ operators are non-public classes that implement IEnumerable<T>.

like image 33
Allon Guralnek Avatar answered Nov 10 '22 13:11

Allon Guralnek


This code is syntactically correct. But the big question is: is it useful, or at least usable in the context where you want to use it? Probably not, since the Main method must be in a public class.

like image 45
Roland Illig Avatar answered Nov 10 '22 11:11

Roland Illig