Search code examples
c#syntaxobjectinstantiation

Diferences between object instantiation in C#: storing objects in references vs. calling a method directly


I have a doubt with the objects declarations in c#. I explain with this example I can do this:

MyObject obj = New MyObject(); 
int a = obj.getInt();

Or I can do this

int a = new MyObject().getInt();

The result are the same, but, exists any diferences between this declarations? (without the syntax)

Thanks.


Solution

  • This isn't a declararation: it's a class instantiation.

    There's no practical difference: it's all about readability and your own coding style.

    I would add that there're few cases where you will need to declare reference to some object: when these objects are IDisposable.

    For example:

    // WRONG! Underlying stream may still be locked after reading to the end....
    new StreamReader(...).ReadToEnd(); 
    
    // OK! Store the whole instance in a reference so you can dispose it when you 
    // don't need it anymore.
    using(StreamReader r = new StreamReader(...))
    {
    
    } // This will call r.Dispose() automatically
    

    As some comment has added, there're a lot of edge cases where instantiating a class and storing the object in a reference (a variable) will be better/optimal, but about your simple sample, I believe the difference isn't enough and it's still a coding style/readability issue.