C# Constructor – Why Using ‘This’ Works

cconstruction

I got two classes.

  • busiObj(created from ancient flat files)
  • key(provides means to tell busiObjs apart)

key has a c'tor that takes a busiObj

public key(busiObj foo)
{
    bar = foo.someThing;
    [...]
}

I want to create the key in the c'tor of the busiObj

public busiObj(...)
{
    myKey = new key(this);
    [...]
}

However: Why on earth does it work?
I firmly expected the compiler to throw something like:
"You cannot reference an object that is currently being made, duh".

So: How is it that I can reference an object while it is still being constructed?

Best Answer

So: How is it that I can reference an object while it is still being constructed?

Presumably Because it's useful (though in a dangerous way) for exactly the scenario you describe, so the language designers decided to allow it.

Technically, it's not a problem at all: while the object is being constructed, its memory must already be allocated, so you can certainly have a reference to it.