Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a class is constructed (instance constructor has finished)?

I have a base class that has a method that gets executed by derived classes. The method is raised by a constructor of the derived class and by some methods or properties in it. I need to determine if that came from inside the instance constructor of that derived class or after that (in runtime).

The following example explains what I need:

public class Base
{
    public Base()
    {

    }

    protected void OnSomeAction(object sender)
    {
        // if from derived constructor EXIT, else CONTINUE
    }
}

public class Derived : Base
{
    public void Raise()
    {
        base.OnSomeAction(this); // YES if not called by constructor
    }

    public Derived()
    {
        base.OnSomeAction(this); // NO
        Raise(); // NO
    }
}

class Program
{
    static void Main(string[] args)
    {
        var c = new Derived(); // NO (twice)
        c.Raise(); // YES
    }
}

The problem is that I cannot change the signature or arguments because I cannot alter derived classes. Basically what I was thinking is to determine if the derived class (sender) is fully constructed.

So the implementation is as is. I cannot do changes in the base class that break derived classes. I can do changes only to the base class :/

Is this possible in some way, good or not? Even some reflection magic or similar hacky approach is unfortunately welcome as this is a must :/.

Thanks!

like image 971
Marino Šimić Avatar asked Sep 08 '11 20:09

Marino Šimić


2 Answers

Is this possible in some way...

Yes

good or not?

Not. But you already knew that.

Nevertheless, here is one way to do it.

protected void OnSomeEvent( object sender, EventArgs e )
{
    var trace = new StackTrace();
    var frames = trace.GetFrames();

    for ( int idx = 0; idx < frames.Length; idx++ )
    {
        MethodBase method;

        method = frames[idx].GetMethod();
        if ( method.ReflectedType == typeof(Derived) && method.IsConstructor )
        {
            return;
        }
    }
    /* Perform action */
}

source

like image 84
Paul Walls Avatar answered Sep 19 '22 12:09

Paul Walls


Nice, clean, proper way - No! Im afraid not.

Hacky way which will no doubt lead to pain and suffering, Perhaps.

Put this inside your OnSomeEvent handler:

var whoCalledMe = new StackTrace().GetFrame(1).GetMethod().Name;

will rad .ctor if called from the constructor, or Main when called from Raise method.

Live example: http://rextester.com/rundotnet?code=DBRLC84297

like image 34
Jamiec Avatar answered Sep 18 '22 12:09

Jamiec