Problem with understanding reference types
-
26-01-2021 - |
Question
I get from WCF service ObservableCoolection
MyTypes = e.Result;
ObservableCollection<MyType> MyTypes // it's a property of _myTypes
<telerik:RadGridView x:Name="grdSrL" ItemsSource="{Binding MyTypes}" SelectedItem="{Binding SelectedMyType, Mode=TwoWay}"
public ShowroomLog SelectedMyType
{
get { return _selectedMyType; }
set
{
if (_selectedSMyType != value)
{
_selectedMyType = value;
RaisePropertyChanged(SelectedMyTypePropertyName);
}
}
}
after I get those collection from web service, selected item is set by grid, and after that I do:
SelectedMyType = null;
Why after that none of item from collection isn't null?
if I do:
var x = new Car();
var y = x;
and
y = null;
then x would be also null;
Why there is different?
Solution
Reference types in C# are effectively object pointers. In your example x
and y
are object pointers, not the objects themselves. If you change a pointer you do not change the object. x would not also become null as you state. That assumption/example is incorrect.
If you called .Clear()
on the collection via either variable, then both pointers to that collection will show 0 entries, but you need to explain what it is you are trying to do so I can explain with a specific example.
.Clear()
would not however destroy any children in the list if there are referenced elsewhere (e.g. by another list).