How to Call the Base Constructor in C#
By FoxLearn 12/2/2024 3:26:29 PM 13
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.
- How to mark a method as obsolete or deprecated in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?
- How to retrieve the Downloads Directory Path in C#
- How to implement keyboard shortcuts in a Windows Forms application
- How to get current assembly in C#