0

I know that its not a good practice to nest a class inside another class, but following is just for fun.

I have the following code

namespace PlayIt
{
    class Class1
    {
        class Class2 : Class1
        {
        }
    }

    class SomeOtherClass
    {
        Class1 objClass1 = new Class1();
        Class2 objClass2 = new Class2();
    }
}

I am able to create the object of class1 but not of class2, Why So? Is there any way to access the class2 outside the class1

leppie
  • 115,091
  • 17
  • 196
  • 297
Pankaj
  • 1,446
  • 4
  • 19
  • 31

3 Answers3

5

I am able to create the object of class1 but not of class2, Why So?

Two reasons:

Firstly, Class1 is implicitly internal, whereas Class2 is implicitly private (because it's nested).

Secondly, you're trying to use just Class2 in a scope where that has no meaning - you'd need to qualify it. This will work fine:

namespace PlayIt
{
    class Class1
    {
        internal class Class2 : Class1
        {
        }
    }

    class SomeOtherClass
    {
        Class1 objClass1 = new Class1();
        Class1.Class2 objClass2 = new Class1.Class2();
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    oh didn't know that by nesting class inside some other class will make it private, I thought class will be always internal or public no matter where they are declared.... Thanks – Pankaj Mar 03 '15 at 08:27
1

Change your "class2" in to internal or public. Then you will be able to access "class2" through "SomeOtherClass". But keep it mind that "Class1" also should not be private or Protected(class1 and SomeOtherClass not derived classes).

You have to understand the concept(Encapsulation) of Access modifiers in OOP

Please refer following Link. What is the difference between Public, Private, Protected, and Nothing?

Community
  • 1
  • 1
0

Because the nested class is private. You can access it if you make it internal or public.

class Class1
{
    internal class Class2 : Class1
    {

    }
}

class SomeOtherClass
{
    Class1 c1 = new Class1();
    Class1.Class2 c2 = new Class1.Class2();
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95