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?
Because the default constructor for A is private, try
protected A() {}
as the constructor.Class
B
automatically calls the default constructor ofA
, if that is inaccessible toB
or there is no default constructor (if you have constructorprotected A(string s) {}
)B
can not be instantiated correctly.The compiler automatically generates the following default constructor in
B
Where
base()
is the actual call to the default constructor ofA
.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.
The constructor on class
B
(which is added by the compiler) needs to call the default (no-args) constructor onA
, however the default constructor is marked asprivate
, which means it can only be called insideA
, hence the error.Change the constructor on
A
toprotected
orpublic
, orinternal
ifB
is in the same assembly.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.
Change
private A()
topublic A()
and you are good to go.