patterncsharpCritical
Calling the base constructor in C#
Viewed 0 times
baseconstructorcallingthe
Problem
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:
Basically what I want is to be able to pass the string message to the base Exception class.
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.
Solution
Modify your constructor to the following so that it calls the base class constructor properly:
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.
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.
Code Snippets
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}Context
Stack Overflow Q#12051, score: 2256
Revisions (0)
No revisions yet.