Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Base Class Property Setter Behavior

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?

like image 855
zhengbli Avatar asked Aug 04 '26 23:08

zhengbli


1 Answers

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
    }
}
like image 65
MarcinJuraszek Avatar answered Aug 06 '26 14:08

MarcinJuraszek