In C# regarding the inheritance of constructors:
Are these statements corrects?
Yes, you're right, constructors are not inherited. So just because Object
has a parameterless constructor, that doesn't mean that String
has a parameterless constructor, for example. From section 1.6.7.1 of the C# 4 spec:
Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.
Yes, the constructor chain of a derived class constructor will always go through its base class constructor... although it may be indirectly, as it could chain to another constructor in the same class via this(...)
instead of base(...)
. If you don't specify either this(...)
or base(...)
, that's equivalent to base()
- calling the parameterless constructor in the base class.
See my article on constructor chaining for more information.
1. You cannot inherit constructors, but you can chain constructors. Example:
public class DerivedClass : BaseClass {
public DerivedClass(object arg):base(arg){}
}
2. Yes, for example, you cannot instantiate a class derived from an object with all private constructors (except in the particular scenario that Jon mentions below in his comment). You cannot skip the constructor of a base class, but you can have multiple overloads, and select the constructor you choose to use.
3. Yes, not sure what the question is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With