Issue with IList properties when instantiating RealmObjects using Reflection: No Set method / Error Object reference not set to an instance of an object


#1

Hi,

assume the following model

namespace My {
public class A : RealmObject {
public IList<B> Bees {get;}
}

public class B : RealmObject;
}

I want to create an instance of A using reflection. Here is what I do.

Type type = Type.GetType("My.A");
var a = Activator.CreateInstance(type);
var beesInfo = a.GetType().GetProperty("Bees");
Type genericList = typeof(List<>);
Type[] typeArgs = { beesInfo.PropertyType.GetGenericArguments()[0] };
Type beesListType = genericList.MakeGenericType(typeArgs);
var bees = (IList)Activator.CreateInstance(beesListType);
beesInfo.SetValue(a, bees, null);

Error --> No Set method for Bees

Now instead if I use

Type type = Type.GetType("My.A");
var a = Activator.CreateInstance(type);
var beesInfo = a.GetType().GetProperty("Bees");
beesInfo.GetType().GetMethod("Add").Invoke(target, new object[] { new B() });

Error --> Error Object reference not set to an instance of an object

Any suggestions how I can instantiate the IList properly and add B objects?


#2

beesInfo is a PropertyInfo, it doesn’t have a method Add. You need to do:

var beesInfo = a.GetType().GetProperty("Bees");
var beesValue = beesInfo.GetValue(a);
beesInfo.PropertyType.GetMethod("Add").Invoke(beesValue, new object[] { new B() });

#3

There seems to be still an issue. Here is the actual code:

namespace My
{
    public class A : RealmObject
    {
        public IList<B> Bees { get; }
    }

    public class B : RealmObject {
        public string Id { get; set; } = Guid.NewGuid().ToString();
    }
}

And in the the App

            Type type = Type.GetType("My.A");
            var a = Activator.CreateInstance(type);
            var beesInfo = a.GetType().GetProperty("Bees");
            var beesValue = beesInfo.GetValue(a);
            beesInfo.PropertyType.GetMethod("Add").Invoke(beesValue, new object[] { new B() });

The last line throws the following error:
Object reference not set to an instance of an object


#4

Here is the link to a sample project:
https://expirebox.com/download/06c445edf7389022e51076e54bd8e9c9.html


#5

Haha, there is no Add method


#6

This works:

                Type type = Type.GetType("My.A");
                var a = Activator.CreateInstance(type) as A;
                var beesInfo = a.GetType().GetProperty("Bees");
                var beesValue = beesInfo.GetValue(a);
                beesInfo.PropertyType.GetMethod("Insert").Invoke(beesValue, new object[] {0,new B()});