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
Release: 2025-01-29 14:51:11
Original
530 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template