«

»

Jul 19

How to: Call a base constructor in C#.Net

Recently I decided I wanted to start creating children classes to handle my Exceptions, but I ran into the issue that I couldn’t quite call the base constructor and I kept asking myself why if I didn’t define a constructor the class couldn’t use the base class and automatically expose them. So below is kind of what I was doing:

class MyExceptionClass : Exception
{
     public MyExceptionClass(string message, string extraInfo)
     {
         //This is where it's all falling apart
         base(message);
     }
}

Basically, after reading up I realized I was misusing the base class and Visual Studio was as kind as to provide a snippet you can use to create your own exception class:

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    [Serializable]
    public class MyException : Exception
    {
        public MyException() { }
        public MyException(string message) : base(message) { }
        public MyException(string message, Exception inner) : base(message, inner) { }
        protected MyException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }

As you can tell you can only use the ‘base()’ method as part of the declaration of the constructor. So… what if I want to modify that message in a special way? Say, you want to prefix all your messages with something. No big deal, you can use static methods to change a parameter this way:

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

         private static string ModifyMessage(string message, string prefix)
         {
             return prefix + message;
         }
    }

So, if you continue to explore all you can do with constructors you come across the fact that you can call one constructor from another (in the same child class). For example:

// Constructor 1
public MyExceptionClass(string message, string extraInfo) :
    this(Convert.ToInt32(extraInfo))  // Calls Constructor 2
{
    // Do nothing.
}

// Constructor 2
public MyExceptionClass(int index)
{
    // Do something?
}

Leave a Reply

%d bloggers like this: