Upon looking into the following code I am unable to figure out the this.AddRange(hoteltasks); on line 21.
I want to know to which collection the AddRange method adds the elements of hoteltasks.
public class HotelViewModel : ObservableRangeCollection<RoomViewModel>, INotifyPropertyChanged
{
// It's a backup variable for storing TaskViewModel objects
private ObservableRangeCollection<RoomViewModel> hoteltasks = new ObservableRangeCollection<RoomViewModel>();
public HotelViewModel()
{
}
public HotelViewModel(Hotel hotel, bool expanded = false)
{
this.Hotel = hotel;
this._expanded = expanded;
foreach (Room task in hotel.Tasks)
{
hoteltasks.Add(new RoomViewModel(task));
}
if (expanded)
this.AddRange(hoteltasks);
}
private bool _expanded;
public bool Expanded
{
get { return _expanded; }
set
{
if (_expanded != value)
{
_expanded = value;
OnPropertyChanged(new PropertyChangedEventArgs("Expanded"));
if (_expanded)
{
this.AddRange(hoteltasks);
}
else
{
this.Clear();
}
}
}
}
}
AddRangeis called onthis, so the contents ofhoteltasksare added tothis.thisrefers to the current instance ofHotelViewModel. Since line 21 is in the constructor,thisrefers to the newly created instance ofHotelViewModel. There is also a second occurrence ofthis.AddRange(hoteltasks);further down the code in the setter ofExpanded. There, the current instance is the instance on which you are accessingExpanded. For more info, see What is the meaning of "this" in C#Although
thisis an instance of something called "HotelViewModel", which doesn't sound like a collection, it is in fact a collection. This is because it is declared to inherit fromObservableRangeCollection<RoomViewModel>, so it has all the behaviours of aObservableRangeCollection<RoomViewModel>, such as being able to haveRoomViewModels stored in it, and being able to have a range ofRoomViewModeladded to it.