By lomaxx


2008-08-15 07:39:23 8 Comments

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.

10 comments

@CShark 2017-03-14 12:38:53

As per some of the other answers listed here, you can pass parameters into the base class constructor. It is advised to call your base class constructor at the beginning of the constructor for your inherited class.

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

I note that in your example you never made use of the extraInfo parameter, so I assumed you might want to concatenate the extraInfo string parameter to the Message property of your exception (it seems that this is being ignored in the accepted answer and the code in your question).

This is simply achieved by invoking the base class constructor, and then updating the Message property with the extra info.

public class MyException: Exception
{
    public MyException(string message, string extraInfo) : base($"{message} Extra info: {extraInfo}")
    {
    }
}

@CShark 2019-03-18 16:01:25

@AndyMiddleditch No, its not. The setter is just private. docs.microsoft.com/en-us/dotnet/api/…

@CShark 2019-03-19 06:33:33

@AndyMiddleditch But you are correct that the previous version of my example would not compile due to the fact that the message attribute has a private setter. I updated my example to work around this (it will now compile). Thanks for the heads-up.

@wchoward 2016-05-27 21:27:43

You can also do a conditional check with parameters in the constructor, which allows some flexibility.

public MyClass(object myObject=null): base(myObject ?? new myOtherObject())
{
}

or

public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)
{
}

@MarzSocks 2016-09-27 04:50:43

Don't you need to remove the words "class" from your example since these are constructors...

@Janus Pedersen 2013-11-11 11:32:42

It is true use the base (something) to call the base class constructor, but in case of overloading use the this keyword

public ClassName() : this(par1,par2)
{
// do not call the constructor it is called in the this.
// the base key- word is used to call a inherited constructor   
} 

// Hint used overload as often as needed do not write the same code 2 or more times

@IAmTimCorey 2013-12-04 14:35:52

I see what you are trying to explain, and you are right. If you have two constructors in one class, you can reference one from the other by using the "this" keyword similarly to how you use "base" when calling the inherited constructor. However, this isn't what the OP asked for so this isn't really the place to add this.

@Donat Sasin 2016-04-07 12:06:09

public class MyException : Exception
{
    public MyException() { }
    public MyException(string msg) : base(msg) { }
    public MyException(string msg, Exception inner) : base(msg, inner) { }
}

@vibs2006 2018-06-10 02:56:13

this is the best answer because it contains constructor overloads as well.

@Fab 2016-01-24 07:34:21

From Framework Design Guidelines and FxCop rules.:

1. Custom Exception should have a name that ends with Exception

    class MyException : Exception

2. Exception should be public

    public class MyException : Exception

3. CA1032: Exception should implements standard constructors.

  • A public parameterless constructor.
  • A public constructor with one string argument.
  • A public constructor with one string and Exception (as it can wrap another Exception).
  • A serialization constructor protected if the type is not sealed and private if the type is sealed. Based on MSDN:

    [Serializable()]
    public class MyException : Exception
    {
      public MyException()
      {
         // Add any type-specific logic, and supply the default message.
      }
    
      public MyException(string message): base(message) 
      {
         // Add any type-specific logic.
      }
      public MyException(string message, Exception innerException): 
         base (message, innerException)
      {
         // Add any type-specific logic for inner exceptions.
      }
      protected MyException(SerializationInfo info, 
         StreamingContext context) : base(info, context)
      {
         // Implement type-specific serialization constructor logic.
      }
    }  
    

or

    [Serializable()]
    public sealed class MyException : Exception
    {
      public MyException()
      {
         // Add any type-specific logic, and supply the default message.
      }

      public MyException(string message): base(message) 
      {
         // Add any type-specific logic.
      }
      public MyException(string message, Exception innerException): 
         base (message, innerException)
      {
         // Add any type-specific logic for inner exceptions.
      }
      private MyException(SerializationInfo info, 
         StreamingContext context) : base(info, context)
      {
         // Implement type-specific serialization constructor logic.
      }
    }  

@Axl 2010-04-28 17:34:20

Note that you can use static methods within the call to the base constructor.

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

     private static string ModifyMessage(string message, string extraInfo)
     {
         Trace.WriteLine("message was " + message);
         return message.ToLowerInvariant() + Environment.NewLine + extraInfo;
     }
}

@Jonathon Cwik 2015-03-11 19:02:55

The Exception class is so locked down that I do find myself doing this a couple times, but also note it's not something you should do if you can avoid it.

@Carlos 2015-05-15 18:32:22

Hi @ChrisS, can I use like ` : base("My default message.")`, how use like this?

@kdbanman 2015-07-09 22:08:11

Sorry, C# newb here. Why do you you call Trace.WriteLine("message was " + message)?

@Nick Whaley 2015-08-21 13:52:17

@kdbanman That just outputs a debug message. No relevant functional purpose.

@Sebastien 2017-01-10 21:27:49

This does not look very SOLID (if you know what I mean) (... SRP ...)

@The Red Pea 2017-05-26 21:38:59

Great answer. Accepted answer doesn't allow for me to do processing; and the followup comment on a workaround assumes I have access to change the base class; I don't. A factory answer assumes that I can control how the class is instantiated; I can't. Only your answer lets me modify something before passing it on to base.

@Aluan Haddad 2017-07-20 22:47:19

There is absolutely nothing harmful about this as long as the intermediate function is morally stateless. Logging is not a good use case, IMO, but normalizing the casing or adding additional seems fine.

@Micheal Johnson 2017-11-12 15:55:00

Thanks so much for this, I needed to create a database context with using to fetch a value to pass to the base constructor and I had no idea how to do this.

@DonO 2018-07-10 20:31:32

If you are in the situation described above. Instead of inheritance you could build your class as a wrapper of the base class as an alternative solution.

@theonlygusti 2019-11-04 14:01:38

How about public MyException(string foo) : base($"Bad {foo}") - will that work? Is that better than a static method?

@Tutankhamen 2015-02-26 04:11:37

class Exception
{
     public Exception(string message)
     {
         [...]
     }
}

class MyExceptionClass : Exception
{
     public MyExceptionClass(string message, string extraInfo)
     : base(message)
     {
         [...]
     }
}

@armanali 2013-02-27 02:22:07

If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

@Sebastien 2017-01-10 21:22:28

This could potentially violates the SOLID principles (SRP), because the responsibility of creating the class is encapsulate with whatever other responsibility the class was suppose to take care of. An abstract factory could be used but might add unnecessary complexity to simple code. Of course violation of the SOLIDs is ok if you know the trade off and the toll it is going to put on your architecture (and how to fix any future issues that might arise from your design decision).

@SnowBEE 2009-12-04 05:03:34

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.

@Jon Limjap 2008-08-15 07:40:22

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.

@Marchy 2009-02-16 21:03:32

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?

@Jon Limjap 2009-02-17 10:46:38

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.

@Roman Starkov 2011-04-17 03:03:18

It is just a method you can call any time, IL-wise. C# just happens to put extra restrictions on top of this.

@Jasper 2014-03-22 19:18:53

@romkyns For a class, yes. For a struct, no. C# doesn't allow you to call a base constructor for structs to make sure they stay (sort of) sane, and for classes to keep things the same across the board. (Compare to C++, where the same thing is true, except the stored on stack or on heap choice is made in the calling code, rather than in the class code, and the same limitation is in place)

@John Weisz 2015-12-08 16:27:51

It is worth noting that the base constructor is called before the method block is accessed. msdn.microsoft.com/en-us/library/ms173115.aspx

@Harald Coppoolse 2015-12-16 07:28:27

It is not a good design if you need to call the base class constructor midway during your constructor. The idea of a constructor is that it does all the work needed to do its task. This has the effect that when your derived constructor starts, the base class is already fully initialized and the derived class is free to call any base class function. If your design is such that you want to do something half way your constructor, then apparently this is not initializing the base class ans thus should not be in the constructor of the base class but in a separate, possibly protected function

@Sebastien 2017-01-10 21:25:00

@JonLimjap does that mean you cannot implement the template method pattern with a constructor?

@Jon Limjap 2017-01-11 02:27:54

@Sebastien Yes and no. If your constructor acts as your template method calling other primitive operations (abstract methods) then it's possible to implement it. Any other implementation needing to call a constructor explicitly from another method or another constructor override is what is prohibited.

@Ken 2019-05-18 00:04:46

Just my two cents if you need to operate / modify things in the base constructor that you are passing in to the derived class - why not manipulate before passing in to the derived class ? That way your base class does what it is to do and your derived class can do whatever else you need it to do. Just seems as though something is not 'clean' when 'modifying' data in the derived class to push into the base class .. if there is something I'am not seeing - I am open to info.

@b1nary.atr0phy 2019-09-15 11:08:18

@Ken "something is not 'clean' when 'modifying' data in the derived class to push into the base class" But that's the point of inheritance... If I have two derived classes, Cat and Dog that derive from the Animal base class, and if I store their names as strings, I'll be able to push their names up the inheritance ladder to the base Animal(string name) constructor. That way, when I access animal.name, it will specifically return "cat" or "dog" instead of the base "animal".

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] What are the correct version numbers for C#?

67 Answered Questions

[SOLVED] What is the difference between String and string in C#?

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

10 Answered Questions

[SOLVED] Call one constructor from another

  • 2010-10-24 16:06:31
  • Avi
  • 448961 View
  • 962 Score
  • 10 Answer
  • Tags:   c# constructor

19 Answered Questions

[SOLVED] Best way to repeat a character in C#

  • 2009-01-04 21:56:59
  • Alex Baranosky
  • 359464 View
  • 781 Score
  • 19 Answer
  • Tags:   c# .net string

18 Answered Questions

[SOLVED] Virtual member call in a constructor

15 Answered Questions

[SOLVED] Call a parent class's method from child class?

21 Answered Questions

[SOLVED] How do I call one constructor from another in Java?

  • 2008-11-12 20:10:19
  • ashokgelal
  • 834641 View
  • 2199 Score
  • 21 Answer
  • Tags:   java constructor

17 Answered Questions

[SOLVED] Interface defining a constructor signature?

Sponsored Content