List properties' CollectionChangeEvent in .Net

Hi,

I want to register a NotifyCollectionChangedEventHandler to a List property, but in my test code I get a runtime exception because the List object assigned by Realm cannot be cast into a IRealmCollection. It also doesn’t implement INotifyCollectionChanged. This is my test code.

namespace RealmTest
{
    public class Customer : RealmObject
    {
        public Customer()
        {
            Name = "Test Name";
            IsActive = false;
            Phone = "8000-0000" ;

            foreach (var t in MyList.GetType().GetInterfaces())
                Console.WriteLine(t);

            // Both throw exceptions
            var v = MyList.AsRealmCollection<string>();
            var w = MyList as IRealmCollection<string>;
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public bool IsActive { get; set; }

        public IList<string> MyList { get; }
   }


class Program
{
    static void Main(string[] args)
    {
        using (var realm = Realm.GetInstance("MyData.realm"))
        {
            realm.Write(() => realm.Add(new Customer()) );
        }
    }
}
}   var v = MyList.AsRealmCollection<string>();
        var w = MyList as IRealmCollection<string>;
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public bool IsActive { get; set; }

    public IList<string> MyList { get; }
}

These are the only Interfaces implemented:

    System.Collections.Generic.IList`1[System.String]
    System.Collections.Generic.ICollection`1[System.String]
    System.Collections.Generic.IEnumerable`1[System.String]
    System.Collections.IEnumerable
    System.Collections.IList
    System.Collections.ICollection
    System.Collections.Generic.IReadOnlyList`1[System.String]
    System.Collections.Generic.IReadOnlyCollection`1[System.String]

I’m new to Realm, so I don’t know what the problem is, and I didn’t find anything helpfull in the docs. I hope someone here can help.

Regards

Thorsten

ps: I’m trying to map a dictionary to two lists because I need a dictionary. But dictionaries are not supported by realm. I’m trying to fire a change event in my dictionary property when the internal list changes. But if someone already has a solution for dictionary properties I’m all ears.

Realm lists become observable only after their parent object is persisted in the database. So something like this should work:

using (var realm = Realm.GetInstane())
{
    var customer = new Customer();
    realm.Write(() => realm.Add(customer));
    var myListCollection = customer.MyList.AsRealmCollection();
}

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.