Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do operations on an inherited base constructor in C#?

Tags:

c#

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?

like image 445
danmine Avatar asked Feb 19 '10 07:02

danmine


People also ask

How do you call a constructor from an inheritance?

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).

Can constructor of base class be inherited?

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.

How do you call a base class constructor?

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 do you call a constructor of a base class from a derived class in C++?

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++


3 Answers

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).

like image 107
Anton Gogolev Avatar answered Oct 06 '22 06:10

Anton Gogolev


Try this:

base(someString == null ? string.Empty : someString.ToLower())
like image 6
Gerrie Schenck Avatar answered Oct 06 '22 06:10

Gerrie Schenck


Try this

public class ClassA
{
    public ClassA(string someString) { }
}

public class ClassB : ClassA
{
    public ClassB(string someString) : base(someString == null  ? "" :  someString.ToLower()) { }
}
like image 3
Adriaan Stander Avatar answered Oct 06 '22 06:10

Adriaan Stander