Kumee
Kumee

Reputation: 211

How to access private class method in nested class

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()
        {
            ...
        }
    }

}

Upvotes: 1

Views: 393

Answers (2)

vgru
vgru

Reputation: 51302

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.

Upvotes: 0

Nipun Anand
Nipun Anand

Reputation: 479

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();
    }
}

Upvotes: 1

Related Questions