Tech Off Post

Single Post Permalink

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

    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.

    Of course you know that the new String has been created.  why would you not?  that's exactly what you are telling the compiler to do. consider:

    namespace ConsoleApplication1
        class Program
            static void Main(string[] args)
                System.Console.WriteLine(new System.String('c', 10).Length);

     here you are telling the runtime to create a new object of type String by calling the constructor with provided parameters, get the Length property, and pass a copy of it to the Console.WriteLine function.  from there it doesn't matter what happens to the String object because it is no longer needed; the WriteLine function has it's own copy (because it's a value type) of what we wanted, so no worries.

    am i right, guys?