Why declare an instance of new class as the base type?
-
I have been working through some code from articles here, altering to suit my needs etc One particular thing puzzles me. Say DgvFilterHost inherits from DgvBaseFilterHost. Why, if a class inherits from a base class, do they declare an instance of the new class as the base type? for example....
public DgvBaseFilterHost FilterHost {
get {
if (mFilterHost == null) {
// If not provided, use the default FilterHost
FilterHost = new DgvFilterHost();It seems it makes additional public properties created in DgvFilterHost inaccessible without casting. Even then I seem to have trouble accessing additional properties. Curious as to why you would not make FilterHost type DgvFilterHost in this example? Thank in advance AussieLew
-
I have been working through some code from articles here, altering to suit my needs etc One particular thing puzzles me. Say DgvFilterHost inherits from DgvBaseFilterHost. Why, if a class inherits from a base class, do they declare an instance of the new class as the base type? for example....
public DgvBaseFilterHost FilterHost {
get {
if (mFilterHost == null) {
// If not provided, use the default FilterHost
FilterHost = new DgvFilterHost();It seems it makes additional public properties created in DgvFilterHost inaccessible without casting. Even then I seem to have trouble accessing additional properties. Curious as to why you would not make FilterHost type DgvFilterHost in this example? Thank in advance AussieLew
There are many reasons for doing this. One reason for doing this is to use Dependency Injection, where you need to refer to a type in your code, but the actual implementation you'd be working on is a derived class. This is also typical behaviour in abstract class factories.
I'm not a stalker, I just know things. Oh by the way, you're out of milk.
Forgive your enemies - it messes with their heads