A library for manipulating .NET expressions.
$ dotnet add package HexagonSoftware.ExpressionTransformsExpression Transformations is a utility library that relies of manipulation of System.Linq.Expressions.Expression instances to simplify
basic tasks.
Following are examples of how and why you might want to use this library.
Sometimes, you want clients to be able to tell an API how to store a datum. Often, developers using such an API want to copy a value into a field or property of an object.
The norm in such cases, is to allow developers to pass an Action<T> into an API. The API will then call that action with appropriate values at the appropriate time.
However, it often feels kludgy to a developer. They have to write expressions that capture values and do the assignment, themselves. For example.
var API = new MyCoolApi();
API.OnVersionNumberChanged += NewVersionNumber => this.VersionNumber = NewVersionNumber;
While it's a small nuisance, it is emblematic of the fact that client-developers are required to tell an API how to store a value, when what they really want to say is where the data should go.
Sometimes that's fine but sometimes it is not.
In the cases where you really want to allow for property mappings, you can define them using the ToSetter extension method in this library.
class MyCoolApi
{
...
public void MapVersionNumberTo(Expression<Func<int>> Selector)
{
OnVersionNumberChanged += SetterFactory.Parameterless.ToSetter(Selector);
}
...
}
This allows for a more semantically-meaningful call from the client's perspective.
var API = new MyCoolApi();
API.MapVersionNumberTo(() => this.VersionNumber);
You can also create a setter expression from a getter expression without knowing the object to be read/written in advance.
For instance, SetterFactory.ForParameter<MyObject>().ToSetter(O => O.Value) will produce a setter Action that accepts both an instance of MyObject
and a paramter suitable to be assigned to Value.
Whenver invoked, that action will assign the Value property on the object passed in as the first parameter.
IObservablesAnother example of the kind of problem you might want to solve with this is binding outgoing values from observables to the setters of properties as in the following code snippet.
var Observable = new Observable();
var Target = new Target();
Observable.BindTo(() => Target.Value);