问题描述:

A question which builds upon To "new" or not to "new"

Foo object1 = new Foo();

// some operations later ...

object1 = new Foo();

Is what I'm attempting to do advisable? and if Foo implements Idispoable, do I need to call dispose before calling the new operator the second time?

网友答案:

Yes, what you're doing in the example is fine.

The object1 variable is simply a reference to an object of type Foo. After the first new assignment it refers to one particular instance of Foo; after the second new assignment it refers to a completely different instance (and the original instance becomes eligible for garbage collection, assuming that there's nothing else referencing it).

And yes, if Foo implements IDisposable then you should dispose it, preferably by using a using block, although my personal preference is to use separate using variables for each block:

using (Foo first = new Foo())
{
    // do something
}

using (Foo second = new Foo())
{
    // do something else
}
网友答案:

In general, if a class implements IDisposable, then it is advisable to ensure that Dispose() gets called. That is almost always the right thing to do.

相关阅读:
Top