Tech Off Post

Single Post Permalink

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

    wkempf wrote:
    ScanIAm wrote:

    There is a completely different thread about a slightly tangential topic, but I'm noticing a number of pieces of example code that concerns me.

    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.

    The other side of the coin, however, is that you could end up with twice as many lines of code if you check every single variable before using it.

    What do you do?

    First, your example is bad:


    However, the idea is there, so I'll address it.  The new String will either be created, thus no problem, or an exception will be thrown and so Length won't be called, so also no problem.  The only problems that exist here exist whether or not you "chain" the calls to the constructor.

    Check the variable before using it?  Like I said, either it worked, and so there's no reason to check, or it threw an exception, so there's no reason to check.  I guess I don't get what you think the problem is?

    Yep, that's what I get for not actually compiling the code and testing it, but it was meant as an example.

    I've seen this used, more often, when adding ListItem to a radiobutton/combobox/dropdownlist. 

    I guess, for me, the fear of using this construct comes from C/C++ training.