.net - Calling the base constructor in C#

ID : 602

viewed : 213

Tags : c#.netinheritanceconstructorc#

Top 5 Answer for .net - Calling the base constructor in C#

vote vote

92

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.

vote vote

83

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;      } } 
vote vote

70

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);     } } 
vote vote

65

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 
vote vote

52

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.

Top 3 video Explaining .net - Calling the base constructor in C#

Related QUESTION?