I have successfully assigned values to Properties and nested Properties using this function
private static void AssignValueToProperty(ObjectAccessor accessor, object value, string propertyLambdaString)
{
var index = propertyLambdaString.IndexOf('.');
if (index == -1)
{
accessor[propertyLambdaString] = value;
// problem above: throws Exception if assigning value to Nullable<T>
}
else
{
var property = propertyLambdaString.Substring(0, index);
accessor = ObjectAccessor.Create(accessor[property]);
AssignValueToProperty(accessor, value, propertyLambdaString.Substring(index + 1));
}
}
However, the assignment throws an InvalidCastException. How to assign nullable values instead using FastMember? For example
public class A
{
public double? SomeValue {get; set;}
}
...
var a = new A();
var accessor = ObjectAccessor.Create(a);
accessor["SomeValue"] = 100; // throws Exception, when assigning 100.0 it works???
FastMember is not going to convert types for you. 100 is an int literal, but the target property is of type decimal?. There is no implicit conversion from int to decimal? (or decimal). 100.0 is a Double literal which implicitly converts to decimal?, and thus the assignment will succeed.
If there is not an implicit conversion, you'll have to perform necessary conversions in your code.
Implicit conversions:
https://msdn.microsoft.com/en-us/library/y5b434w4.aspx
Explicit conversions:
https://msdn.microsoft.com/en-us/library/yht2cx7b.aspx
FastMember has nothing related to type conversion within it's toolbox, so this is the solution I came up with as Extension Method for FastMember
ObjectAccessor
:Can be called this way: