How to Call the Base Constructor in C#

By FoxLearn 12/2/2024 3:26:29 PM   13
In C#, you can call a base class constructor from a derived class using the base keyword.

This is commonly used when a derived class needs to pass arguments to a constructor of its base class.

How to Call the Base Constructor in C#?

For example, Calling the base constructor with no parameters

public class BaseClass
{
    public BaseClass()
    {
        // Base class constructor called.
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass() : base() // Calls the base class constructor
    {
        // Derived class constructor called.
    }
}

For example, Calling the base constructor with parameters

public class BaseClass
{
    private string message;

    public BaseClass(string message)
    {
        this.message = message;
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass(string message) : base(message) // Call to base class constructor with an argument
    {
        // Derived class constructor called.
    }
}

If I inherit from a base class and need to pass data from the derived class constructor to the base class constructor, how can I achieve this?

For instance, when inheriting from the Exception class.

class MyException : Exception
{
     public MyException(string message, string extraInfo)
     {
         // This is where it's all falling apart
         base(message);
     }
}

Update your constructor as shown to correctly call the base class constructor.

public class MyException : Exception
{
    public MyException(string message, string extrainfo) : base(message)
    {
        // other stuff here
    }
}

A constructor cannot be called within a method because it is only executed when an object is created, which is why you're encountering errors when trying to call it inside the constructor body.