The correct way to delete and reuse an object

  • Thread starter Thread starter Flix
  • Start date Start date
F

Flix

When making c# programs, I usually write code like this:

[...]
SomeType myType=null;
[..]
void Init()
{
myType=new SomeType();
}
[...]
void SomeFunction()
{
if (myType==null) return;
else
{
[...]
}
}

My first question is how to do to delete an initialized object:
myType=null is enough?
Or myType.Dispose();myType=null; ?

My second question is how to delete and reinitialize it in a correct way:
myType=new SomeType(); deletes the first instance of myType automatically ?
(even if myType is a runnig Thread?)

Thank you in advance.
 
Flix said:
When making c# programs, I usually write code like this:

[...]
SomeType myType=null;
[..]
void Init()
{
myType=new SomeType();
}
[...]
void SomeFunction()
{
if (myType==null) return;
else
{
[...]
}
}

Hmm... I can't say I find that a useful pattern myself. Surely myType
would only be null if the parent object hadn't been initialised
properly, which should mean you throw an exception of some description.
My first question is how to do to delete an initialized object:
myType=null is enough?
Or myType.Dispose();myType=null; ?

If you're using a type which implements IDisposable, you should call
Dispose on it if you allocated it, when you're finished with it. If
it's a member variable, you should implement IDisposable yourself.

Usually, you don't need to do anything. Local variables will fall out
of scope appropriately, and in my experience it's rare to have a member
variable which becomes useless before the object itself becomes useless
- at which point the values of its constituent variables don't matter
anyway.
My second question is how to delete and reinitialize it in a correct way:
myType=new SomeType(); deletes the first instance of myType automatically ?

Nope. It just stops that particular variable from preventing the
instance (of SomeType - it's not an instance of myType) that myType
previously referred to from being garbage collected.
(even if myType is a runnig Thread?)

myType is a variable, that's all. It can't be a thread or a Thread
(those being two somewhat different things; the latter is a way of
manipulating and finding out about the former). It's value can be a
reference to a Thread, but that won't stop the thread represented by
that Thread from running.
 
Back
Top