Tech Off Post

Single Post Permalink

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

    Sven Groot wrote:
    ScanIAm wrote:
    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.

    Ignoring that String is a bad example because you can do "Bob".Length (as was mentioned), I still don't see what you're getting at.

    What is it you want to check? Any error conditions that cause the object not to be created would throw an exception.

    Code like what evildictaitor wrote:
    MyObject o = new MyObject();
    if( o == null )
       throw new Exception();

    That's completely pointless. O can never be null after a "new", since if the object couldn't be created an exception would be thrown (e.g. an OutOfMemoryException).

    Exactly, and I'm fine with that, now, but it doesn't 'feel' right.  That's my own cross to bear Smiley

    string s = "bob";

    just seems safer.