I have this piece of code, and error is generated, just because I haved added into a constructor for its class.
class NestedClass
{
class A
{
A() {}
}
class B
{
// no constructor
}
public static void run()
{
A a = new A(); // error
B b = new B(); // no error
}
}
And error is:
NestedExample.A is inaccessible due to protection level
Please help me explain this.
Thanks :)
Your constructor is private
. Default access modifier for class members is private
.
class A
{
A() {}
}
this is correct implementation
class A
{
public A() {}
}
Define your constructor as public
public A() { }
Your constructor for class A
is private
Private Constructors (C# Programming Guide) - MSDN
Note that if you don't use an access modifier with the constructor it will still be private by default.
The reason it is working for B is that you haven't specified any constructor and for default constructor:
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation
Define the constructor as public
public class A
{
public A() {}
}
Your constructor of A is private. It cannot be accessed from outside of A. At the same time, B does not have a consuctor at all and therefore gets a default public constructor.
you need to specify, the default one is private and while in the case of B the compiler provides a public parameterless constructor for you., so you have to specify it for class A
class A
{
public A() { }
}
Make your nested classes public
and the problem will be solved. Your run method is public but the classes you want to use are not public and this gives problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.