A base class is there to "provide" features to the derived classes, and to
"offer" common code. Enforcement comes from someone taking you up on your
offer. A base class is not there to "enforce" good programming practice on
the part of the derived class.
Therefore, find a way to offer the feature that the derived class needs. Do
it in a way that YOU can enforce good practices. Then, you can get what you
want.
You've had some good suggestions here. Either derive an intermediate class
that already contains the SqlConnection member, or add the SqlConnection
member to your class. (I like the former more than the latter, but I do not
know what your class does).
Enforcement for the sake of a bit of utility code (not coding Dispose
multiple times) is an expensive proposition in the long run.
Besides, if a derived class is so poorly written that it does not properly
dispose of it's resources, it may have many other bugs as well... bugs that
need to be refactored out. Protecting bad code can only lead to later
problems.
My $0.02
--- Nick
" Bob" <bo*******@yahoo.com> wrote in message
news:ew*************@TK2MSFTNGP12.phx.gbl...
I want to find a way to detect the existance of the private member of a
particular type in the derived class from inside the base class itself and
call its Dispose() method. Reflection GetFields() only returns public
members and I would like to avoid using reflection due to its performance
impact. Not sure if using an enumerator would help. The code below
illustrates what I want to do. If this is doable, the benefit would be
that there is no need to write the same Dispose code in every derived class
that has the SqlConnection variable.
//Base class
public class MyBase {
..........
public Dispose() {
//if a private field of SqlConnection exists, call its Close()
method
}
}
//Derived class
public class MyClass : MyBase {
.......
//This derived class happen to have a member of the SqlConnection.
//The member name (variable name) may vary in different derived
classes. private SqlConnection _conn;
.......
}