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:
    ScanIAm wrote:
    I've done this myself, but how 'safe' is it:

    Console.WriteLine(new String("Bob").Length);

    The part that concerns me is the accessing of the function 'Length' when you don't really know that the new String has actually been created.

    You absolutely know that the new String has been created before Length is called. An exception will be thrown if the String could not be created.

    [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 interesting, and would be a bug in the CLR.

    You won't be able to test for it either since

    1:  MyObject o = new MyObject();
    2:  if(null == o)
    3:    throw new Exception();
    4:  var result = o.LongRunningMethod();

    If what you say is correct then lines 2 and 3 are superflouous since o could be garbage collected between 2,3 and 4.

    To protect against it you could do

    MyObject o = new MyObject();
    var result = o.LongRunningMethod();

    But in fairness this is a bug that should be fixed by Microsoft rather than coded around, and you should write an bugreport if you find in your code that this is happening.