tags:

views:

18498

answers:

4

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

+58  A: 

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.

Jon Limjap
I think you may have missed the point. The problem was about calling a base constructor midway through the overriden constructor. Perhaps the data-type of the base constructor is not the same or you want to do some data moulding before passing it down the chain. How would you accomplish such a feat?
Marchy
If you need to call the base constructor in the middle of the override, then extract it to an actual method on the base class that you can call explicitly. The assumption with base constructors is that they're absolutely necessary to safely create an object, so the base will be called first, always.
Jon Limjap
+15  A: 

Its also worth noting you can chain constructors in your current class by substituting "base" for "this".

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

You can pass inner exception to one of the constructors.

SnowBEE
+3  A: 

Note you can use methods within the call to the base contructor...

    class MyExceptionClass : Exception
    {
         public MyExceptionClass(string message, string extraInfo) : 
         base(ModifyMessage(message, extraInfo))
         {
         }

         private string ModifyMessage(string message, string extraInfo)
         {
             Trace.WriteLine("message was " + message);
             return message.ToLowerInvariant() + Environment.NewLine + extraInfo;
         }
    }
Axl
ModifyMessage needs to be static here..
Sprintstar