3

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 :)

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
hqt
  • 29,632
  • 51
  • 171
  • 250

6 Answers6

7

Your constructor is private. Default access modifier for class members is private.

   class A
   {
      A() {}
   }

this is correct implementation

   class A
   {
      public A() {}
   }
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
  • 1
    thanks. I come from java, so I think default for class members is public :D – hqt Dec 28 '12 at 10:39
  • 2
    @hqt, I think in Java the default is `package`, which is visible inside the package See [this](http://stackoverflow.com/questions/3530065/which-is-the-default-access-specifier-in-java) – Habib Dec 28 '12 at 10:47
6

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:

Constructor - MSDN

Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation

Habib
  • 219,104
  • 29
  • 407
  • 436
3

Define the constructor as public

public class A
{
    public A() {}
}
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
3

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.

Ravi Y
  • 4,296
  • 2
  • 27
  • 38
1

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() { }
}
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

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.

TimVK
  • 1,146
  • 6
  • 16