1

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
amelian
  • 436
  • 1
  • 6
  • 17

3 Answers3

4

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
3

It's mostly syntax.

The main difference is that you can't use the instance of MyObject in the second example. Also, it may be nominated for Garbage Collection immediately.

MarkO
  • 2,143
  • 12
  • 14
  • Can you e xplain to me what is in this case de GC?? – amelian May 07 '14 at 10:48
  • @AMGHoshi Short answer: GC is the Garbage Collection. Instances of objects no longer referenced in code will be deleted from memory by the GC process. This *may* happen immediately, but most likely at an indeterminate moment in the future. Long answer: See MSDN. – MarkO May 07 '14 at 10:56
1

No, technically they are the same.

The only thing I would suggest to consider in this case, as if the function does not actual need of instance creation, you may consider declare it static, so you can simply call it like:

int a = MyObject.getInt();

but this naturally depends on concrete implementation.

Tigran
  • 61,654
  • 8
  • 86
  • 123