Reputation: 1524
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
Upvotes: 0
Views: 83
Reputation: 92
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?
Upvotes: 1
Reputation: 9394
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();
}
Upvotes: 0
Reputation: 1503290
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();
}
}
Upvotes: 5