Calling the base constructor in C#
Solution 1
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.
Solution 2
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;
}
}
Solution 3
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);
}
}
Solution 4
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
Solution 5
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.
Nathan Kurz
Co-Founder of KeyPay - Simple, intuitive, cloud-based payroll system for small to medium Australian businesses
Updated on September 02, 2021Comments
-
Nathan Kurz over 2 years
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.
-
Quibblesome over 15 yearsIts also worth noting you can chain constructors in your current class by substituting
this
forbase
. -
NoWar almost 4 years
-
user1601201 over 3 yearsInstead of saying "it's all falling apart" it's a lot more helpful to just post the error you're getting
-
گلی almost 3 yearsTry: public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } }
-
David Mays about 2 years@Quibblesome I haven't been able to find an example substituting .this for .base. I'm probably not phrasing it right, but do you have any examples? My question is if you do substitute, do you no longer need :base in the arguments and can just use .base in the constructor?
-
-
Marchy about 15 yearsI 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?
-
Roman Starkov about 13 yearsIt is just a method you can call any time, IL-wise. C# just happens to put extra restrictions on top of this.
-
IAmTimCorey over 10 yearsI 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.
-
Jonathon Cwik about 9 yearsThe 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.
-
kdbanman almost 9 yearsSorry, C# newb here. Why do you you call
Trace.WriteLine("message was " + message)
? -
Nick Whaley over 8 years@kdbanman That just outputs a debug message. No relevant functional purpose.
-
John Weisz over 8 yearsIt 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 over 8 yearsIt 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 over 7 yearsThis 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).
-
The Red Pea almost 7 yearsGreat 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 almost 7 yearsThere 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.
-
vibs2006 almost 6 yearsthis is the best answer because it contains constructor overloads as well.
-
DonO almost 6 yearsIf 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.
-
VimNing over 3 years@HaraldCoppoolse: I don't agree. If I remember it right, iOS Swift actually does this conversely that the derived class should not depend on the base class is a good design, instead the base constructor is called last line in the block. Without the dependency of data the modification about base classes won't affect the derived class(es). And notice that in Language Specification definition/mechanism for function overloading adopted this idea. (in C++, C#).
-
David Con about 2 yearsIt is posible to have a condition to use 2 different base constructors? I mean one of them with 2 params and the other with 3 params?
-
dynamiclynk about 2 years@DavidCon sure you can create multiple constructors with different signatures\params in your base class, use them like above.
-
David Con about 2 yearsI can´t call to diferent base constuctors. I need some think like this: public MyClass(object myObject=null): base(myObject==null ? invokeConstructorBaseA: invokeConstructorBaseB){} Furthermore, ConstructorBaseA has 2 parameters and ConstructorBaseB has 3 parameters. Is there any why of invoke them?