Category Archives: Reflection

Copy an entire synced Realm

In our company, we use as mobile Database with the ROS Cloud to sync data between mobile devices and the server. Main advantage is, that we can build Apps in a fraction of time, without juggling with synchronization.

One of our main challenges was the disability to copy data from one realm to another. But there is still a good solution for this, even though you have to do a lot of coding for that.


There are a lot of reasons, why copying realms is a really neat feature. First of all would be versioning your data. But it’s also very neat, when you have several instances (for development, testing etc.) to copy the whole data when you go productive or need some test data in development.

Challenge 1: generating the Schema

When we copy one realm to another, we actually don’t know the used types. We could include a library which contains the types, but then our “RealmCopy” will only work for a specific realm, which is really baloney. That’s as if you develop a copy-program, that can only copy text-files.

So we need to read the source realm, get the schema and create the same schema in the destination. In .Net we can open a realm dynamically, which is pretty cool, because this gives us a chance to get the information we need. Only problem – we can not create or change a schema on a dynamically opened realm.

Solution? We can create dynamic types, and open the destination realm, this will automatically create a schema on the destination realm. (It’s really a little bit awkward, but that’s currently the only chance in .Net – with Javascript, we can mutate the realm directly, but that’s probably due to the nature of that language)


Open a realm as dynamic:

var username = "";
var password = "";
var realmUrl = "";
var realmName = "TestRealm";
var user = await User.LoginAsync(Credentials.UsernamePassword(username, password, false), new Uri(realmUrl));

var configuration = new FullSyncConfiguration(new Uri(realmName, UriKind.Relative), user)
IsDynamic = true
var srcRealm = await Realm.GetInstanceAsync(configuration);

now we can go through the scheme and create types:

var types = new List();
foreach (var scheme in schemasToProcess)
// create an assembly for our type
var assemblyName = new AssemblyName($"SomeAssemblyName{name}");
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
// create an module for the type
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
// get the typebuilder as
var typeBuilder = moduleBuilder.DefineType(name,
TypeAttributes.Public |
, parent);
// add properties to type
foreach (var prop in schema)
var attributes = new List();
Type propType;
// woven property is needed, so Realm will add it to the destination schema
if (prop.IsPrimaryKey)
// add primary key attribute
else if (prop.IsIndexed)
// add indexed attribute

// get the property type
propType = prop.GetPropertyType(knownTypes);

// set required attribute, when its not nullable
if ((prop.Type & PropertyType.Nullable) != PropertyType.Nullable)

// create the property
MyTypeBuilder.CreateProperty(typeBuilder, prop.Name, propType, attributes.ToArray());

In one of my previous blog posts I mentioned how to create types using the TypeBuilder, so I won’t code it out here.
The function GetPropertyType is an extension, it’s just a mapping of the Realm-PropertyType to a CLR type.
Now we can open the destination Realm:

var configuration = new FullSyncConfiguration(new Uri(realmName, UriKind.Relative), user);
configuration.ObjectClasses = types;
var destRealm = await Realm.GetInstanceAsync(configuration);

Challenge 2: copying the realm

This doesn’t actually seem to be a challenge. We go through all objects in source realm and copy it to a new RealmObject, which is created in destination. You can actually use our generated types to open the source realm and use straight reflection for mapping all properties. But be careful, if you did something wrong, you would probably mutate the source realm (what you might not want). You can stick to the dynamic Realm instead and use CallSiteCache to read the properties and reflection to set it to the destination object. (more infos)

Challenge 3: cascaded objects

An object may not only reference atomic types, but also have other RealmObjects as properties. It can even contain cycles. This is really tricky, I solved it by initially creating a TypeBuilder for each SchemaItem, then we can use this TypeBuilder as a PropertyType, without building the actual type. Creating objects can be done recursively, but keep track of the objects, you already created, so you can avoid cycles.

If you have any questions, feel free to ask. ..have fun coding.

read and write properties on dynamic objects in .NET/C#

Ok, the headline sounds a little bit funny, because first of all, dynamic objects have no properties. Also you can not use reflection on a dynamic type, because it’s dynamic. What I actually want to do, is to access values of a dynamic object by its name – but I don’t know the name of the property on compile time, but during execution.

I want to do something like that:

dynamic obj = GetDynamicObject();
string myPropertyValue = DynamicExtension.GetValue(obj, "MyProperty");
DynamicExtension.SetValue(obj, "MyProperty", "some cool value");

So how can we do this? Reflection is not possible, and not all dynamic types impement IDictionary like ExpandoObject.

But how can we achieve this? By looking at the disassembled code, of a dynamic class, and the way it is accessed, we can find out, how we can access it ourself…

dynamic dynObj = new TestClass
  TestProperty = "Hello World",
  TestInt = 20
var val = dynObj.TestProperty;
dynObj.TestProperty = "Hello C#";

Because I don’t want to flood this post, I just copied the essentials from the IL. Basically there are 2 parts:
1. create a Binder
2. create a CallSite to execute the getter/setter.

// the getter
            var binder = Binder.GetMember(
                new CSharpArgumentInfo[] { 

 CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.NamedArgument, null)

            var getter = CallSite<Func<CallSite,object,object>>.Create(binder);
            var val = getter.Target(getter,  dynObj);

// the setter
var setterBinder = Binder.SetMember(
    new CSharpArgumentInfo[] {
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) });
// the IL actually uses string as value type, but we use object here, to be more flexible
var setter = CallSite<Func<CallSite,object,object,object>>.Create(setterBinder);
setter.Target(setter, dynObj, "Hello C#");

So now just wrap it up to our two functions:

    public static class DynamicHelper
        public static object GetValue(object obj, string name)
            var binder = Binder.GetMember(
                        new CSharpArgumentInfo[] {

            var getter = CallSite<Func<CallSite,object,object>>.Create(binder);
            return getter.Target(getter, obj);

        public static void SetValue(object obj, string name, object value)
            var setterBinder = Binder.SetMember(
                new CSharpArgumentInfo[] {
                  CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                  CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null) });
            // the IL actually uses string as value type, but we use object here, to be more dynamic
            var setter = CallSite<Func<CallSite,object,object,object>>.Create(setterBinder);
            setter.Target(setter, obj, value);

C# Creating Types during runtime (.Net Core)

This is really fancy stuff, no one would probably never ever get along doing this. And I actually have no real straight forward “all day” use-case, I would ever recommend this for. But guess what, there is always an exception.

So why am I doing this?

My situation is the following: On one hand I have a database (actually a database). I want to copy that Realm into another Realm, but I didn’t find a tool, doing that for me. Because that is an object oriented database, we need the model definitions right when opening the database, but I wanted to create a tool, to copy data from one realm to another, without actually knowing the class models at all. So there is a pretty neat construct called “DynamicRealm”, one can just open those by passing a parameter while opening the Realm called “IsDynamic”. Then I don’t need to have the actual classes in my code. When I then open an existing Realm, it shows me all information about the schema, that is stored in the database (properties, attributes, etc.)…

So far, so good, .. I can read data. But my destination Realm is absolutely blank, no schema, no data. And in .NET there is no method implemented to create my own schema. There is only one thing I can do – adding Types while opening the Realm, and Realm will take care of creating the schema. So I need to impement type-creation from the schema during runtime. 

Creating the type during runtime

But before we create a type, we need to create an Assembly and Module, that type is going to be in. Be careful to use names, that aren’t already used. There are 3 Builders we use from the assembly System.Reflection.Emit : AssemblyBuilder, ModuleBuilder, TypeBuilder . In fact this part is pretty easy:

var parent = typeof(BaseClass); // the type of the baselcass for this type (can be null)
var name = "MyCoolTypeName"; // name of the new type

// 1. create assembly name
var assemblyName = new AssemblyName($"SomeAssemblyName{name}");
// 2. create the assembly builder
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
// 3. that is needed to create a module builder
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
// 4. and finally our TypeBuilder (a public class)
TypeBuilder tb = moduleBuilder.DefineType(name,
TypeAttributes.Public |
, parent);
Type type = tb.CreateType(); // of type Type, we can even create instances of that type

But when we want to create a real POCO we also need to add some properties to that type.

Add properties to the created Type (TypeBuilder)

This is not as easy, as it sounds like. We have to be aware, what is actually needed to create a property:
1. a backing field
2. a get method
3. a set method
Since we are in runtime mode, we need to create the method bodys in IL (which is the byte code used by .NET), so we cannot use plain C#.
(Be careful: all this can only run on systems with JIT compiler, so you cannot do that in UWP (with .Net Toolchain active) or iOS, Mono should be fine, but I didn’t test it yet)

So how to find out what IL to use? Just create a TestClass and produce some IL (I prefer using dotPeek from JetBrains):

.method public hidebysig specialname instance string
    get_Text() cil managed
    IL_0000: ldarg.0      // this
    IL_0001: ldfld        string RealmCopy.TestClass::'_backingField'
    IL_0006: ret

  } // end of method TestClass::get_Text

  .method public hidebysig specialname instance void
      string 'value'
    ) cil managed
    IL_0000: ldarg.0      // this
    IL_0001: ldarg.1      // 'value'
    IL_0002: stfld        string RealmCopy.TestClass::'_backingField'
    IL_0007: ret

  } // end of method TestClass::set_Text

After that, we can just write down the code for adding a property to the TypeBuilder:

public static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
   if (propertyType == null) // when the propertytype is null, we assume, it's the Type itself (so we set it to the TypeBuilder)
       propertyType = tb;

   if (propertyType == typeof(IList&amp;amp;lt;&amp;amp;gt;)) // same thing here for a IList with no generic type parameter -&amp;amp;gt; we assume it's the type (we could probably do that for every generic type without type parameter)
       propertyType = propertyType.MakeGenericType(tb);

   FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); //creates the backing field
   PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

   //get method
   MethodBuilder getPropMthBldr = tb.DefineMethod(
      "get_" + propertyName
       | MethodAttributes.SpecialName
       | MethodAttributes.HideBySig
      , /*returnType*/ propertyType
      , /*parameter types*/ Type.EmptyTypes); // see IL for the right MethodAttributes
   ILGenerator getIl = getPropMthdBldr.GetILGenerator();
   // create the code in the get method
   getIl.Emit(OpCodes.Ldarg_0); //this
   getIl.Emit(OpCodes.Ldfld, fieldBuilder); //backingfield

   // set method
   MethodBuilder setPropMthdBldr =
      "set_" + propertyName,
       | MethodAttributes.SpecialName
       | MethodAttributes.HideBySig
      , /*returnType*/ null
      , /*parameter types*/ new[] { propertyType }); // see IL for the right MethodAttributes

   ILGenerator setIl = setPropMthdBldr.GetILGenerator();
   // create the code in the set method
   setIl.Emit(OpCodes.Ldarg_0); //this
   setIl.Emit(OpCodes.Ldarg_1); // 'value'
   setIl.Emit(OpCodes.Stfld, fieldBuilder); // backingfield


   // add methods to the propertyBuilder

Error 0xC000041D using GetCallingAssembly()

Reflection is very cool, the meta data system of .Net is pretty cool. You can create objects of a given class, without knowing it at compile time, by just looking it up and instantiating it using reflection. But how can I look up a type? Some times you only know the name of a type you want to create, without knowing the correct assembly. Let’s say we have an assembly, that holds a service implementation to create a object:

class MyService
  object GetObject(string typeName)

The class we want to create, is in the assembly from where that function gets called. That is ok, but we don’t know that assembly at compile time, we can only find it out, when the function gets called. But how?

The regular solution would be, to use System.Reflection.Assembly.GetCallingAssembly(). But when we do this in .Net Nativ, we get an exception at runtime:

Unhandled exception at 0x78A7B264 (Windows.UI.Xaml.dll) in BlankApp3.UWP.exe: 0xC000027B

I think this is a bug within the .Net native compiler. But how can we find a workaround for that problem?

1. using a fully qualified type name

object GetObject(string typeName)
  var type = Type.GetType(typeName);
  return Activator.CreateInstance(type);

You can then actually use the complete name, including the namespace, when calling the function. (Something like: GetObject(“BlankApp3.Views.MainPage”)), so it’s not possible to lookup a type by name. But for our use case, it is enough.

2. lookup the assembly by name

object GetObject(string assemblyName, string typeName)
  var assemblies = AppDomain.CurrentDomain.GetAssemblies();
  var assembly = assemblies.FirstOrDefault(asm => 
  var type = assembly.GetTypes().FirstOrDefault(t => 
  return Activator.CreateInstance(type);

This is the most flexible solution in our case (but it takes more time). You can even look through all loaded assemblies, and find types by name. Please be aware that there is another bug, preventing you from getting all types from all loaded assemblies (the solution can be found on stackoverflow).

How to assign properties (fast) in C#?

Ok, the short answer to that question is easy, just assign it directly. That’s it, and this is the shortest blog post ever. But actually that’s not the point, I wanted to make. There are a bunch of methods to assign a class-property with a specific value, but how do they differ, when it comes to performance. Even though I can guess, that Reflection is probably very expensive, I have no real feeling to what degree. My measurements also came up with a surprise, I didn’t expect when I started this out.

The setting

For me, it’s very interesting to investigate that on .NET Standard with C# in UWP, because we are currently developing an App with Xamarin.Forms. Please keep in mind, that the results may differ on .NET Core or other targets, but I think there will be no dramatic difference.

We will generate a TestClass with a property Sum, afterwards, we will read the value, add an iteration variable to it, and write it back to the property. Let’s do that more than 10000 times, so we get a good feeling for the performance.

What possibilities we have?

Let’s do some brainstorming on what kind of methods we have to read and assign a value to a property.

  1. Direct assignment
    obj.Sum = obj.Sum + i
  2. Reflection
    var type = typeof(TestClass);
    var sumProp = type.GetProperty("Sum");
    var val = (int)sumProp.GetValue(obj);
    sumProp.SetValue(obj, val + i);
  3. Function
    var func = (Action)((TestClass o, int n) => { o.Sum += n; });
    func(obj, i);
  4. Dynamic
    dynamic objDyn = new TestClass();
    objDyn.Sum = i + objDyn.Sum;

Let’s start the test

First of all, we try to find out how long the first call takes. I assume, that the first access of a property takes longest. Afterwards it’s probably way faster. But enough talk about what might happen, get it on:


The measurements are in 10-7 s. As we can see, the first calls with dynamic objects is very slow. All other methods are really close to each other. Is this just because of the Debug mode? How about compiling the code with .Net native? Maybe we can distinguish the methods better in Release Mode.


This seems to be a better solution. We can see, that direct assignments and function calls are very close, and take no time at all. The function call is a little bit slower, just because of the overhead of the function. Reflection is slightly better in .Net nativ (app. 50%) and dynamic calls are 95% faster in native build, than they are in debug mode.

But when we think about a real App, the first call isn’t very interesting. Just assume we have an App to manage our Customers. A customer object has 20 properties (name, street, zip code, etc.), we have about 5000 customers, and a page that shows all customers in a table. Our Model needs to be mapped to a ViewModel to show it on the screen. That gives us 100.000 assignments. I think this is a very realistic scenario, we can investigate on. (we will skip the first assignment call in our measurements)


What we can see, is that (as expected) function-calls and direct assignments take nearly the same time. Dynamic assignments are surprisingly fast, and reflection is very slow. But what does “slow” mean in that context? Have a look at the times measured:

  1. direct: 1,2 ms
  2. function: 2,0 ms
  3. dynamic: 7,6 ms
  4. reflection: 74 ms

We got so far, let’s have a look at the same setting with .Net native builds:


Where is direct and function? Both measurements are under 1ms, so there is a real boost. But there is a big surprise – What happened to dynamic????

  1. direct: 0,12 ms ( -90%)
  2. function: 0,3 ms ( -85%)
  3. reflection: 45 ms ( -39%)
  4. dynamic: 249 ms ( +337%)

I’ll investigate that issue on one of my future posts, if you have any ideas, how this could happen, please feel free to add a comment.


There is an eligible reason, why Microsoft introduced the dynamic objects. Dynamic objects are very common in scripting languages like PHP or JavaScript. When you use it to parse responses of a Rest-API or just want to read data from a Json in your own object structure. This is really neat because you don’t have to create an own class structure, that is only used as an intermediate layer.

I am very curious, so I also tried to use ExpandoObjects and in contrast to that a Dictionary<,>:

  1. ExpandoObject: 800 ms
  2. Dictionary<,>: 5 ms

So you should definitely try to use Dictionaries instead of any dynamic approach. It’s a little bit harder to code, but it seems to be worth it.

When it comes to reflection, you probably can not avoid it – it is also one of the big strength of C# and the .Net Framework, that makes it so flexible even when it’s still a strongly typed programming language. Although I will be careful in future developments, to find more conservative solutions, when possible.

Almost forgot… the winner is


direct assignment… I dare you knew that before 🙂