Detecting if class is still running constructor

  • Thread starter Thread starter Pavils Jurjans
  • Start date Start date
P

Pavils Jurjans

Hello,

I have this class, which has an indexer and some methods, and the
constructor of this class makes several calls to them. I would like the code
in methods to have different behaviour depending whether the constructor is
still running (and current method is called from the constructor), or the
class is already initialized, and the method is called from other context.
Is there any way to discover this?

Thanks,

-- Pavils
 
Pavils,
Is there any way to discover this?

You could set a flag to indicate that the constructor is calling

class Foo
{
public Foo()
{
_inCtor = true;
DoStuff();
_inCtor = false;
}

public void DoStuff()
{
if ( _inCtor )
Console.WriteLine( "Called from constructor" );
else
Console.WriteLine( "Not called from constructor" );
}

bool _inCtor;
}



Mattias
 
Is there any way to discover this?

No, you have to add a private field to do this. I like to use the
following pattern:

class Foo {
private bool _initialized = false;

public Foo() {
// ... constructor is running...
this._initialized = true;
}
}
 
Back
Top