Search code examples
c#xamarinxamarin.formsvaluetuplebindableproperty

Property in a new instance of class and previously created instance of same class are referenced same memory


// Interface 
public interface IItem
{
    Collection Collection
    {
        get;
        set;
    }
}

public class Collection : BindableObject
{
    public static readonly BindableProperty ItemsProperty =
        BindableProperty.Create("Items", typeof(ObservableCollection<People>), typeof(Collection), new ObservableCollection<People>(), BindingMode.TwoWay, null, null);
    public ObservableCollection<People> Items
    {
        get { return (ObservableCollection<People>)GetValue(ItemsProperty); }
        set { this.SetValue(ItemsProperty, value); }
    }
}

//Model class.
public class People
{
    public string Name
    {
        get;
        set;
    }
}


//Core logic implementation.
public class SourceItems :BindableObject, IItem
{
    public static readonly BindableProperty CollectionProperty =
        BindableProperty.Create("Collection", typeof(Collection), typeof(SourceItems), new Collection(), BindingMode.TwoWay, null, null);

    public Collection Collection
    {
        get { return (Collection)GetValue(CollectionProperty); }
        set { this.SetValue(CollectionProperty, value); }
    }
}


Public class MainPage()
{
        var firstsource = new SourceItems();
        firstsource.Collection.Items.Add(new People() { Name= "People1" });
        firstsource.Collection.Items.Add(new People() { Name = "People2" });
        firstsource.Collection.Items.Add(new People() { Name = "People3" });

        var secondSource = new SourceItems();
        secondSource.Collection.Items.Add(new People() { Name = "People4" });
        secondSource.Collection.Items.Add(new People() { Name = "People5" });
        secondSource.Collection.Items.Add(new People() { Name = "People6" });
}

Here i have created two different object for class 'SourceItems' after executing above code instance of firstsource.Collection.Items holds 6 items and secondSource.Collection.Items also holds same 6 items. it should be 3.

please clarify me what i'm doing wrong.

Image

i have showed both the instance value while debugging.


Solution

  • The firstsource and secondSource is different in your code, while firstsource.Collection is the same Collection as secondSource.Collection.

    Because when you perform set/get method(add new items) to firstsource.Collection or secondSource.Collection, they all point to public static readonly BindableProperty CollectionProperty, it's a static property so it's shared in all SourceItems instances as Jeppe Stig Nielsen mentioned in his answer.

    That's why firstsource.Collection.Items holds 6 items and secondSource.Collection.Items also holds same 6 items. They are the same Collection.