Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling the base constructor in C#

If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?

For example, if I inherit from the Exception class I want to do something like this:

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

Basically what I want is to be able to pass the string message to the base Exception class.

like image 866
lomaxx Avatar asked Aug 15 '08 07:08

lomaxx


People also ask

How do you call a base class constructor?

To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly. The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.

Is Base constructor always called?

The base constructor will be called for you and you do not need to add one. You are only REQUIRED to use "base(...)" calls in your derived class if you added a constructor with parameters to your Base Class, and didn't add an explicit default constructor.

Do you have to call base constructor C#?

yes you can call base class constructor from derived class in C#, In the inheritance hierarchy, always the base class constructor is called first. In c#, the base keyword is used to access the base class constructor as shown below.

What is base in constructor?

base (C# Reference)A base class access is permitted only in a constructor, an instance method, or an instance property accessor. It is an error to use the base keyword from within a static method. The base class that is accessed is the base class specified in the class declaration.


1 Answers

Modify your constructor to the following so that it calls the base class constructor properly:

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

Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.

like image 98
Jon Limjap Avatar answered Sep 28 '22 08:09

Jon Limjap