Invoking the basic constructor in C

What if I inherit from the base class and want to pass something from the constructor of the inherited class to the constructor of the base class?

For example,

If I inherit from the Exception class, I want to do the following:

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 string messages to the basic Exception class.

#1 building

Modify your constructor to the following code so that it calls the constructor of the base class correctly:

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

Note that the constructor is not something you can call at any time in a method. This is the reason for the error in calling the constructor.

#2 building

If the basic constructor needs to be called immediately because the new (derived) class requires some data manipulation, the best solution is to use the factory method. What you need to do is mark the derived constructor as private, then create a static method in your class to handle all the necessary work, then 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);
    }
}

#3 building

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

You can pass an inner exception to one of the constructors.

#4 building

It's true that base (something) can be used to call the constructor of the base class, but if overloaded, 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

#5 building

Note that you can use static methods in calls 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;
     }
}

Added by nullified on Mon, 09 Dec 2019 09:57:51 +0200