Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Run something after derived classes constructor

I have a desing question. Lets say I have a base class, and many derived classes.

class MyBase
{ 
    MyBase()
    {
        Record();
    }

    void Record()
    {
        /// this line is able to handle every object
        Recorder.Process(this);
    }
}

class DerivedA : MyBase
{ 
    public int SpecialPropertyOfA { get; set; }
    DerivedA(int specialPropertyOfA)
    {
        SpecialPropertyOfA = specialPropertyOfA;
    }
}

class DerivedB : MyBase
{ 
    public string SpecialPropertyOfB { get; set; }
    DerivedA(string specialPropertyOfB)
    {
        SpecialPropertyOfB = specialPropertyOfB;
    }
}

As you may deduce, I want to record derived classes with all their properties set. But the above example cannot record the special properties of derived classes since they are not set when the Record method called.

One way to overcome this is to make Record method protected and call it as the last line of derived classes constructors. But this violates my base principals(every derived class should be recorded right after initialization). I want to make this mandotory by design.

Any ways to handle this?

Upvotes: 0

Views: 163

Answers (1)

Matias Cicero
Matias Cicero

Reputation: 26281

Take a look again at what you're trying to do.

Remember that base class constructor is called before the derived class's constructor.

MyBase()
{
    Record();
}

void Record()
{
    Recorder.Process(this); // <-- What is "this" ?
}

What would be the value of this at this point?

The instance has not been constructed yet, the derived class's constructor hasn't event been called so there's no reference to this, hence, you can't use it here.

You'll have to call this method after the instance has been fully constructed.


A way to overcome this is using a factory method:

public static class MyBaseFactory
{
     public static MyBase CreateDerivedA()
     {
         int specialPropertyOfA = // ...
         MyBase instance = new DerivedA(specialPropertyOfA);
         Recorder.Process(instance);
         return instance;
     }

     public static MyBase CreateDerivedB()
     {
         string specialPropertyOfB = // ...
         MyBase instance = new DerivedB(specialPropertyOfA);
         Recorder.Process(instance);
         return instance;
     }
}

Upvotes: 1

Related Questions