Any ideas how to create a generic fluent setter?
Imagine that I've the following class
internal class ClonableExampleClass
{
public ClonableExampleClass()
{
}
public string ExampleString { get; set; }
public int ExampleInt { get; set; }
public ClonableExampleClass ExampleNestedClass { get; set; }
public List<ClonableExampleClass> ExampleList { get; set; }
}
I want to:
public class Program
{
public static Task Main(string[] args)
{
var exampleClass = new ClonableExampleClass
{
ExampleInt = 1
};
exampleClass
.With(opt => opt.ExampleInt).Set(2)
.With(opt => opt.ExampleString).Set("test");
var json = JsonSerializer.Serialize(exampleClass);
}
}
and the expected json to be:
{"ExampleString":"test","ExampleInt":2,"ExampleNestedClass":null,"ExampleList":null}
I've created an extension method With:
public static FluentBuilderObjectValueSetter<T> With<T>(this T sourceObject, Func<T,object> action)
{
var property = action(sourceObject);
return new FluentBuilderObjectValueSetter<T>(sourceObject, action);
}
Which returns FluentBuilderObjectValueSetter (I've removed the interface to make it more easy to test, for now)
public class FluentBuilderObjectValueSetter<TObjectType> //:IFluentBuilderObjectValueSetter<TObjectType>
{
private readonly TObjectType _sourceObject;
private object _sourceValue;
internal FluentBuilderObjectValueSetter(TObjectType sourceObject, ref object sourceValue)
{
_sourceObject = sourceObject;
//_action = action;
_sourceValue = sourceValue;
}
public TObjectType Set<TMemberType>(TMemberType value)
{
_sourceValue = value;
return _sourceObject;
}
}
But is not setting the object value