Welcome to TechNet Blogs Sign in | Join | Help

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.

 

Published Tuesday, January 02, 2007 6:05 PM by wigunara
Filed under:

Comments

# re: psuedo deferred base constructor call from a derived class (C# .NET)

Wednesday, January 31, 2007 3:17 AM by CouldntResist

Why not call an abstract/virtual method defined in the derived class as the first line of the base class constructor?

# re: psuedo deferred base constructor call from a derived class (C# .NET)

Wednesday, January 31, 2007 9:39 AM by CouldntResist

... oops but now I realise you are using Exception as the base, a class you dont have access to. Therefore you'd have to define another class in the chain to do that...

# re: psuedo deferred base constructor call from a derived class (C# .NET)

Friday, February 02, 2007 8:26 AM by wigunara

Even if you define another class in the chain, you still cannot perform actions on the parameters to the base constructor as you'll have to call the base constructor within your intermediary class constructor before its own code gets executed.

Anonymous comments are disabled
 
Page view tracker