Home >Backend Development >C++ >How Do I Call a Base Class Constructor in C# Inheritance?

How Do I Call a Base Class Constructor in C# Inheritance?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-29 14:51:11536browse

How Do I Call a Base Class Constructor in C# Inheritance?

C# Inheritance: Invoking the Base Class Constructor

In C# inheritance, you often need to initialize the base class's properties and fields before adding your derived class's specific initialization. This is achieved by calling the base class's constructor within the derived class's constructor.

The syntax for calling the base class constructor is straightforward:

<code class="language-csharp">public <DerivedClass>(<arguments>) : base(<arguments>)
{
    // Derived class-specific initialization
}</code>

The : base(<arguments>) portion explicitly calls the base class constructor, passing any necessary arguments. The derived class constructor then executes after the base constructor completes.

Illustrative Example:

Let's say we have an Exception class (a built-in C# class). To create a custom exception, we inherit from Exception and pass a message to the base constructor:

<code class="language-csharp">public class CustomException : Exception
{
    public CustomException(string message, string detail) : base(message)
    {
        // Store additional detail (this is specific to our derived class)
        Detail = detail;
    }

    public string Detail { get; set; }
}</code>

Here, base(message) calls the Exception class's constructor, providing the error message. The derived class then adds its own Detail property.

Important Consideration:

You cannot directly call a base class constructor from within a method; it must be done within the derived class's constructor using the : base(...) syntax. This ensures proper initialization order.

The above is the detailed content of How Do I Call a Base Class Constructor in C# Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn