Example
public class ClassA
{
public ClassA(string someString){}
}
public class ClassB : ClassA
{
public ClassB(string someString):base(someString.ToLower()){}
}
I call the inherited ClassB constructor. I pass in a null. ToLower() throws an exception on a null. I want to check for a null before that happens. How can I do this?
In case of inheritance if we create an object of child class then the parent class constructor will be called before child class constructor. i.e. The constructor calling order will be top to bottom. So as we can see in the output, the constructor of Animal class(Base class) is called before Dog class(Child).
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript.
How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++
Simple. Using null-coalescing operator:
public ClassB(string someString) :
base((someString ?? "").ToLower())
{
}
Or using ternary operator
public ClassB(string someString) :
base(someString == null ? "" : someString.ToLower())
{
}
Better yet, I'd suggest you to add a no-arg constuctor to ClassB
, which will call base(string.Empty)
.
Try this:
base(someString == null ? string.Empty : someString.ToLower())
Try this
public class ClassA
{
public ClassA(string someString) { }
}
public class ClassB : ClassA
{
public ClassB(string someString) : base(someString == null ? "" : someString.ToLower()) { }
}
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