inheritance and hiding of properties

  • Thread starter Thread starter Art
  • Start date Start date
A

Art

hey!

problem solved, but without good explanation, over the cause.

the probelm was:

public class Parent
{
protected string[] people_I_hate = {"Frank","Dasy"};
public Parent()
{ ... }
public void ListBehated()
{ ... }
}

public class Child : Parent
{
protected new string[] people_I_hate = {"Frank",
"Dasy","Policeman","Bank"};
public Child():base()
{ ... }
}

when i called "ListBehated()" from a "child"-object it always was just
frank and dasy. why didnt it recognize the property in the child-
class? there where no compile-errors. at first i didnt even use the
"new"-modifier and the compiler said something like "... property in
child class hides property in parent class. use 'new'-modifier if
intended." but anyways, with or without 'new'-modifier it did not work
as intended.

i googeled a bit for inheritance and property-hiding, but didnt find
anything useful.

i solved the problem by putting the initialization of the property
into the constructor. now it works as intended. any explanation, why
it didnt work before? (... it took me hours to work around this prob.
it was a service i had to run on a remot machine. so debugging was
like compiling, installing, running, looking up the eventlog-entries;
changing code, compiling, installing, .... HELL!)

but for the future: why is this not possible? i use inheritance and
property/memeber-hiding to extend or change a system, when i dont want
to change the original code. and if there is a property like the above
it kills, if it is not hideable by a child-property.

thanks,
art
 
problem solved, but without good explanation, over the cause.

Okay, here goes:

1) You weren't writing properties, you were writing fields. There's a
big difference here, because properties can be overridden - fields
can't. They're not treated polymorphically. That's at the heart of
what went wrong.
2) When the compiler warned you that you were hiding the base class
field, it wasn't suggesting that you should add "new" offhand - it was
asking whether you really, really meant to hide the field.
3) When you come across a problem in a difficult-to-debug situation,
the first thing to do is reproduce it in a situation where it's *not*
difficult to write code. Create a short but complete program that
demonstrates the problem (see http://pobox.com/~skeet/csharp/complete.html)
and then you'll have a very quick code/test cycle. (An alternative is
to create a unit test if you've got unit testing set up, of course.)
4) I keep all fields private to start with, which makes this kind of
mistake harder to come by. Personally I'd have changed the base class
constructor to take the array as a parameter, so that your child class
could pass them in, rather than setting them itself in its
constructor.

Jon
 
Back
Top