Reputation: 10815
I am confuse on what is the default constructor access modifier and what does this MSDN statemtn says
If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs.
Because when i applied this with a test program it fails. I can make an object or class that is inheriting another class thogh there is no exteranal parameerless constructor defined.
class A
{
}
class B : A
{
}
class C
{
public void main()
{
B objB = new B();// as per MSDN here should be the compile time error.
}
}
[Source]
Upvotes: 4
Views: 8415
Reputation: 4860
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public.
In your example, all the classes A, B, C has been created with a default internal parameterless constructor.
Since both classes are in the same assembly and are internal with internal constructors by default you are not getting a compilation error. But if you declare a non-accessible constructor (e.g. private or protected) in your class B you will get a compilation error in your example.
Upvotes: 3
Reputation: 5242
The compiler creates parameterless constructor if you don't create one yourself, so as per the MSDN page, your example actually ends up looking like this;
class A
{
public A(): base() {}
}
class B : A
{
public B(): base() {}
}
Your call to new B()
will ultimately end up calling A's constructor. However, if you created an explicit constructor for A which is private;
class A
{
private A() {}
}
class B : A
{
}
Then this translates to;
class A
{
private A() {}
}
class B : A
{
public B(): base() {}
}
Which will fail to compile with an error about A's constructor being inaccessible.
Upvotes: 3
Reputation: 3816
If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs.
If a constructor is not defined for a class, the compiler will automatically generate a public default constructor.
Upvotes: 4
Reputation: 13484
From Using Constructors
Unless the class is static, classes without constructors are
given a public default constructor by the C# compiler in order to
enable class instantiation.
Upvotes: 3
Reputation: 67316
If a constructor is not defined for a class, the compiler will automatically generate a public
default constructor.
However, if there is a constructor defined that limits the access, then the compiler will throw.
for example, this should throw an exception:
class A
{
private A() {}
}
class B : A
{
}
Upvotes: 2