psuedo deferred base constructor call from a derived class (C# .NET)
I was building an exception class derived from the Exception class when I stumbled upon a problem - I wanted to perform some processing on the constructor parameters of my derived class before passing the results onto the base constructor for the exception - in the case of Exception, a string parameter for a message.
It appears the base constructor must be called before any derived constructor, which precludes performing any complex work before passing any parameters to the base class constructor.
public class DerivedClass : Exception
{
public DerivedClass(string rawData) : base(rawData) {
// this is executed after the base constructor
}
}
However, you can work around this by performing any processing work in a static method which you can call within the call to the base constructor
public class DerivedClass : Exception
{
public DerivedClass(string rawData) : base(DerivedClass.ProcessData(rawData)) {
// this is executed after the base constructor
}
private static string ProcessData(string rawData)
{
// this will be executed before the base constructor is called
// do stuff with the rawData and return processed data
return(processedData);
}
}
Obviously you're working with a static method rather than an instance method so you cannot access instance data, but if you can live with this limitation then it's quite a useful technique.