Beachwalker Beachwalker - 1 month ago 21
C# Question

How to set nested property value using FastMember

I get an exception when I try to set a nested member Property using FastMember. For example when having these classes

public class A
{
public B First { get; set; }
}

public class B
{
public string Second { get; set; }
}


and I want to set
First.Second
of an instance to
"hello"
.

var b = new B{ Second = "some value here" };
var a = new A{ First = b };
var accessor = ObjectAccessor.Create(a);
accessor["First.Second"] = value; // this does not work and gives ArgumentOutOfRangeException


I can't split it up into ["First"]["Second"] because I don't know the depth at this point. Is there a magical access for nested properties or do I have to split the hierarchy myself?

Answer

You need to traverse the object graph using multiple ObjectAccessor instances.

public static void UseFastMember()
{
    var b = new B { Second = "some value here" };
    var a = new A { First = b };
    var value = "hello";
    var a_accessor = ObjectAccessor.Create(a);
    var first = a_accessor["First"];
    var b_accessor = ObjectAccessor.Create(first);
    b_accessor["Second"] = value;
}
Comments