Reputation: 529
I have an application which needs re initialization every time I process. something like :
private void method(int someValue, int someValue2)
{
obj.val1 = someNewValue;
obj1.Val2 = someNewValue2;
}
This method will be called repeatedly. So I doubt is it okey to re initialize the object every time? something like;
private void method(int someValue, int someValue2)
{
obj = new object();
obj.Val1 = someNewValue;
obj1.Val2 = someNewValue2;
}
I know assigning null
to an object is nothing fruitful to do with.
or should I implement IDisposable
? The problem is I need fresh values every time.Assigning will be ok in this scenario? I dont know what will happen to the already allocated object if i reinitialize as shown in second method.
Upvotes: 0
Views: 700
Reputation: 35380
"Reference objects" need to be disposed (by calling Dispose()
) only if they use unmanaged memory. All such objects (in the .NET class libraries) implement IDisposable
. Managed objects, on the other hand, are automatically collected (deleted) by the Garbage Collector behind-the-scene. In fact there is no direct way of deleting a managed object. You should not worry about such objects. As soon as they go out of scope, GC will eventually release their memory.
Simply assigning a new value to a managed variable releases the reference of the previous value and therefore makes it available for deletion by the GC.
Upvotes: 5
Reputation: 1579
is this Object a custom class? If so i would write a "Reset()" method to do all the resetting you'd need.
for example you would call
private void method(int someValue, int someValue2)
{
obj.Reset();
obj.Val1 = someValue;
obj1.Val2 = someValue2;
}
and in the Reset function you would do whatever you need to consider the object "re-initialised"
i.e
public void Reset()
{
this.Val1 = 0;
this.Val2 = 0;
this.Name = "";
this.Date = DateTime.MinDate;
//You get the Idea, reset whatever needed to whatever you need.
}
using this function you can also then, in the constructor simply call "Reset();" so you know the values are the same when another method calls "Reset" on this object along with a new object being made.
Upvotes: 3