Embedd_0913
Embedd_0913

Reputation: 16545

Why am I getting an "inaccessible due to protection level" error?

I am getting this error:

'CTest.A.A()' is inaccessible due to its protection level.

when compiling this code:

public class A
{
    private A()
    {
    }
}

public class B : A
{
    public void SayHello()
    {
        Console.WriteLine("Hello");
    }
}

Can anyone explain why?

Upvotes: 2

Views: 2935

Answers (5)

Robert
Robert

Reputation: 3302

It's because A's constructor is private, but B's constructor is public. When you construct B (which constructs A as well) there is no way to access A's private constructor.

Upvotes: 0

MPelletier
MPelletier

Reputation: 16657

The constructor for A is private, it cannot be accessed from outside. If you want to create an instance of A from outside, make the constructor public or protected.

Upvotes: 2

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60684

Change private A() to public A() and you are good to go.

Upvotes: 1

thecoop
thecoop

Reputation: 46098

The constructor on class B (which is added by the compiler) needs to call the default (no-args) constructor on A, however the default constructor is marked as private, which means it can only be called inside A, hence the error.

Change the constructor on A to protected or public, or internal if B is in the same assembly.

Upvotes: 3

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

Because the default constructor for A is private, try protected A() {} as the constructor.

Class B automatically calls the default constructor of A, if that is inaccessible to B or there is no default constructor (if you have constructor protected A(string s) {}) B can not be instantiated correctly.

The compiler automatically generates the following default constructor in B

public B() : base()
{
}

Where base() is the actual call to the default constructor of A.

Upvotes: 14

Related Questions