Reputation: 712
So I have a base class, which has a property ItemList
:
public class BaseClass {
private List<Item> itemList;
public List<Item> ItemList {
set {
itemList = value;
LoadItems();
}
}
public void LoadItems() { ... }
}
And now I have a derived class, in which I want to change the behavior of the function LoadItems()
. So I did this:
public class DerivedClass {
public new void LoadItems() { ... }
}
But when I set the property ItemList
, only the base LoadItems()
is called. Is there anyway I can call the new LoadItems()
instead?
Upvotes: 2
Views: 1110
Reputation: 149618
Make LoadItems()
virtual and override it in your derived class:
public class Base
{
public virtual void LoadItems() { ... }
}
public class Derived : Base
{
public override void LoadItems() { ... }
}
Upvotes: 2
Reputation: 24916
Use this code:
public class BaseClass {
// ....
public virtual void LoadItems() { ... }
}
public class DerivedClass : BaseClass {
public override void LoadItems() { ... }
}
Upvotes: 3
Reputation: 125660
Make your property virtual
and mark derived class implementation with override
, not new
: Knowing When to Use Override and New Keywords (C# Programming Guide)
public virtual List<Item> ItemList {
set {
itemList = value;
LoadItems();
}
}
public override List<Item> ItemList {
set {
// do something
// you can also call base.ItemList
// to get base class property implementation
}
}
Upvotes: 5