简体   繁体   中英

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.

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM