Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling both a base constructor and a parameterless constructor?

Here's something that struck me, and I'm wondering if this is at all possible.

To make a long story short - here's the code:

public class NotificationCollection : ObservableCollection<Notification>
{
    public NotificationCollection() : base()
    {
        this.CollectionChanged += NotificationCollection_CollectionChanged;
        this.PropertyChanged += NotificationCollection_PropertyChanged;
    }

    public NotificationCollection(IEnumerable<Notification> items)
        : base(items)
    {
        this.CollectionChanged += NotificationCollection_CollectionChanged;
        this.PropertyChanged += NotificationCollection_PropertyChanged;
    }
(....)
}

As you can see, I'm duplicating code. Had I not been creating an inherited class, I'd write

public NotificationCollection(IEnumerable<Notification> items)
    : this() //I can just call the empty constructor
{
    //do stuff here...
    //however, in case of inheritance this would be handled by base(items)
}

So, my question is - can I call both the base class constructor as well as this constructor?

like image 244
Shaamaan Avatar asked Dec 08 '22 13:12

Shaamaan


1 Answers

Short answer: No, you can't.

Workaround:

public NotificationCollection() : this(Enumerable.Empty<Notification>())
{
}

public NotificationCollection(IEnumerable<Notification> items)
    : base(items)
{
    this.CollectionChanged += NotificationCollection_CollectionChanged;
    this.PropertyChanged += NotificationCollection_PropertyChanged;
}
like image 154
Daniel Hilgarth Avatar answered May 10 '23 19:05

Daniel Hilgarth