1

How can I access the method DoSomething() here? I can't access it when I create an object of type SomeClass.

On the other hand, what is the use of having a private class inside a public class?

public class SomeClass
{
    public string str = string.Empty;

    private class SomePrivateClass
    {
        public void DoSomething()
        {
            ...
        }
    }

}

Mario Cervera
  • 671
  • 1
  • 8
  • 19
Kumee
  • 201
  • 1
  • 4
  • 11
  • 9
    You can access `DoSomething` from methods of `SomeClass` (using an instance of `SomePrivateClass`). – Dirk Aug 25 '14 at 10:14
  • https://dotnetfiddle.net/dh62Hk – dcastro Aug 25 '14 at 10:17
  • 1
    [Private inner classes in C# - why aren't they used more often?](http://stackoverflow.com/questions/454218/private-inner-classes-in-c-sharp-why-arent-they-used-more-often) – CodeCaster Aug 25 '14 at 10:17
  • Since you marked you question as OOP - it's generally advised not to use nested types when you intend to access members of the nested type. – lapadets Aug 25 '14 at 10:49
  • Where do you want to access DoSomething from? From SomeClass? Or are you trying to access it from a completely different class? – bobbyalex Aug 25 '14 at 10:51

2 Answers2

1

You need to create the object of the nested class inside the outer class:

public class SomeClass
{
    public string  str= string.Empty;

    private class SomePrivateClass
    {
         public void DoSomething()
         {

         }
    }
    public void CreateObjectOfSomePrivateClass()
    {
        SomePrivateClass obj = new SomePrivateClass();
        obj.DoSomething();
    }
}
Nipun Anand
  • 479
  • 2
  • 6
0

DoSomething is an instance method, and a public one, meaning that any code which has access to the definition of that type (class), can in fact invoke that method. And since SomePrivateClass is a private class of SomeClass, then it can only be instantiated within SomeClass. You should concentrate on reading more about the difference between static and instance members (e.g. this MSDN article).

Having said that, one thing that a private class can do is access private fields of a parent class (both instance and static, but again you need to have an instance of a parent class in order to call its instance methods), which other classes can't.

vgru
  • 49,838
  • 16
  • 120
  • 201
  • Nitpick: "any code which can instantiate an object of that type" - or, more precisely, any code which can get hold of an instance of that type (even if it cannot itself instantiate the type). – O. R. Mapper Aug 25 '14 at 11:11
  • 1
    @O.R.Mapper: yes, that's correct, or maybe even better, as long as the class definition is visible to the client code, since you can easily get an instance of a private or an internal class through a public interface or its base type which doesn't have to expose the method at all. – vgru Aug 25 '14 at 11:22