Constructor question, reference problem
Hello
I have two questions.
1. Is it possible to call base constructor in the body of the current constructor?
I want code like this:
class MyClass
{
public MyClass()
{
// some code here
base();
}
}
2. I don't understand this code. I have an object that returns reference to the DataTable it contains. I am wondering how come that in following code t variable remains valid:
void MyClass()
{
DataTable t;
void SomeFunc(){
using ( ObjectWithTable owt = new ObjectWithTable() )
{
t = owt.Table;
}
}
}
The GC will free the owt as soon as it exits the using statement, but I can still access its table over t.
Thanks.
AlanPosted Sep 18, 2008, 10:36 AM
What the 'using' statement does is to call the Dispose() method on the ObjectWithTable object referenced by 'owt' when the statement ends. That in turn probably calls the Dispose() method on the DataTable object referenced by its Table property.
However, this isn't the same thing as actually destroying the objects and reclaiming their memory. This will only take place when there are no longer any references to the objects and the GC gets around to it. This is why I suggested setting 't' to null.
If it's a problem waiting for the GC to do its thing, then you can try and force an immediate garbage collection by calling the GC.Collect() method.
MiodragPosted Sep 18, 2008, 9:24 AM
MiodragPosted Sep 18, 2008, 9:15 AM
AlanPosted Sep 18, 2008, 7:39 AM
The answer to the first question is 'no'. You can only call the base constructor before any code in the derived class constructor executes using the ' : base()' syntax.
In fact, if you don't use this syntax, the parameterless constructor of the base class is still called automatically.
The answer to the second question is that 't' is a field, not a local variable, of the DataTable type. Although the DataTable to which it points should be disposed of (along with its containing object) when the 'using' statement ends, 't' will still point to that object which may not actually be destroyed by the GC until some time later but in the meantime will be in an unstable state. It's therefore safest to set 't' to null when the 'using' statement ends.