C
C P
I'm coming from Delphi where I have to explicitly create and destroy
instances of objects. I've been working through a C#/ASP.NET book, and many
of the examples repeat the same SqlConnection, SqlDataAdapter etc. objects,
so I thought I'd create a class with a bunch of factory methods to create my
classes for me. But, I'm unclear about how garbage collection works, and if
it is safe to do this. It seems to compile, but am I asking for trouble?
For example:
public class MyClass {
static SqlConnection MyRepeatedConn() {
return new SqlConnection("SomeConnectionString");
}
}
public class SomeOtherClass {
public void DoSomething() {
SqlConnection cnn = MyClass.MyRepeatedConn();
// Do stuff with cnn
}
}
At what point will a connection created by MyRepeatedConn() be available to
be destroyed? From what (I think) I've read, the connection could be
"garbage collected" as soon as MyRepeatedConn() exits (although the garbage
collection will likely happen later on). Am I in danger of my code in
DoSomething() failing, or is the garbage collector smart enough to know that
cnn holds a reference to the SqlConnection in question, and therefore will
leave it alone until DoSomething() has also exited?
Thanks,
Chris
instances of objects. I've been working through a C#/ASP.NET book, and many
of the examples repeat the same SqlConnection, SqlDataAdapter etc. objects,
so I thought I'd create a class with a bunch of factory methods to create my
classes for me. But, I'm unclear about how garbage collection works, and if
it is safe to do this. It seems to compile, but am I asking for trouble?
For example:
public class MyClass {
static SqlConnection MyRepeatedConn() {
return new SqlConnection("SomeConnectionString");
}
}
public class SomeOtherClass {
public void DoSomething() {
SqlConnection cnn = MyClass.MyRepeatedConn();
// Do stuff with cnn
}
}
At what point will a connection created by MyRepeatedConn() be available to
be destroyed? From what (I think) I've read, the connection could be
"garbage collected" as soon as MyRepeatedConn() exits (although the garbage
collection will likely happen later on). Am I in danger of my code in
DoSomething() failing, or is the garbage collector smart enough to know that
cnn holds a reference to the SqlConnection in question, and therefore will
leave it alone until DoSomething() has also exited?
Thanks,
Chris