Calling both the base constructor and the constructor without parameters?

Here is something that struck me, and I wonder if this is possible at all.

In short, here is 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 am duplicating the code. If I did not create an inherited class, I would 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 the constructor of the base class, as well as the constructor of this ?

+4
source share
2 answers

Short answer: No, you cannot.

Workaround:

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

You can bind to only one constructor - either in the current type ( this(...) ) or in the base type ( base(...) ). If you need to call different base constructors in these two cases, then no - you cannot use this() code. However, you can move this code to a separate method and call it from both places (provided that readonly members are not involved).

However, you also should not subscribe to your own events - this is usually a code smell. In this case, it is probably best to check the override :

 public class NotificationCollection : ObservableCollection<Notification> { public NotificationCollection() : base() {} public NotificationCollection(IEnumerable<Notification> items) : base(items) {} protected override void OnCollectionChanged( NotifyCollectionChangedEventArgs e) { // YOUR CODE HERE base.OnCollectionChanged(e); } protected override void OnPropertyChanged(PropertyChangedEventArgs e) { // YOUR CODE HERE base.OnPropertyChanged(e); } } 
+6
source

Source: https://habr.com/ru/post/1500882/


All Articles