What is a context which allows MemberwiseClone() to be called

RogerSchlueter-7899 1,466 Reputation points
2025-08-07T22:08:10.11+00:00

I have a Person class and a ocPeople class defined as:

ocPeople = ObservableCollection(Of Person)

ocPeople is used as the ItemsSource for a ComboBox. What I want to do is to create another ObservableCollection(Of Person) which is the original with the Person selected in the ComboBox removed. Here is how I do that:

Private Sub cbxPeople_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles cbxPeople.SelectionChanged
	CurrentPerson = CType(cbxPeople.SelectedItem, Person)
	Dim oc As ObservableCollection(Of Person) = CType(ocPeople.MemberwiseClone(), ObservableCollection(Of Person))
	oc.Remove(CurrentPerson)
End Sub

This yields an error:

'Object.Protected Overloads Function MemberwiseClone() As Object' is not accessible in this context because it is 'Protected'.

What context would allow MemberwiseClone() to be called? If MemberwiseClone() is not used, what is the best way to create a new ObservableCollection with just one member removed?

Windows development | Windows App SDK
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 123.6K Reputation points
    2025-08-08T21:02:04.38+00:00

    Since MemberwiseClone is protected, it can be used in derived classes (which uses Inherits in their declarations).

    Probably it is not required. Check if this works:

    Dim oc As New ObservableCollection(Of Person)(ocPeople.Except({CurrentPerson}))
    

    It will create a new collection that does not include the CurrentPerson.

    Maybe it is more suitable to just remove the person from the original collection:

    ocPeople.Remove(CurrentPerson)
    

    The person should disappear from ComboBox automatically.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.