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.
精彩评论