Tech Off Post

Single Post Permalink

View Thread: is 'new object().property' or 'new object().method()' a good idea?
  • User profile image

    Curt Nichols wrote:


    [Edge case ahead.]

    Now, in the case of

        new MyObject().LongRunningMethod();

    the instance of MyObject may be garbage collected before LongRunningMethod returns. This usually doesn't cause a problem, but it can; to cause a problem usually involves a questionable design decision (e.g., a disposed MyObject cleans up a field, and this happens to occur after LongRunningMethod's last reference to your MyObject instance but before using a locally stored reference to that field). I can make it happen but I don't expect to see it in the wild.

    This is not a problem and this is why:

    1) if LongRunningMethod() acceses fields on MyObject instance the "this" parameter is passed on the stack to the method meaning you have a rooted reference to the object instance, the method call practicaly is like this

    newobj MyObject //Returns a reference in the stack

    so when the LongRunningMethod is called there is a reference in the stack pointing at the
    MyObject instance. Also because LongRunningMethod acceses fields of the object it keeps a referente to the object instace in it's own stack frame and the object won't be garbage colected.

    LongRunningMethod() doesn't access any fields on MyObject instance so that means even if the object is garbage colected (because now the jit can optimize the method to eliminate the reference from the stack) the method will never try to dereference a null object (the this pointer) so won't get a NullReference exception.

    To test it you can even try to call with reflection a instance method that doesn't access any fields passing a null value and it will work.

    NullReference is only thown when you try to dereference a null pointer and not by calling a method (if that method doesn't try to dereference a null pointer the exception will never be thrown)