Skip to content

Instantly share code, notes, and snippets.

@forki
Created March 1, 2011 07:57
Show Gist options
  • Save forki/848791 to your computer and use it in GitHub Desktop.
Save forki/848791 to your computer and use it in GitHub Desktop.
FSharpRecordExtensions to allow (mutable) With-Syntax in C#
public static class FSharpRecordExtensions
{
public static string GetPropertyName<T, TProperty>(this Expression<Func<T, TProperty>> expression)
{
return ((MemberExpression) expression.Body).Member.Name;
}
public static Tuple<T, FieldInfo> Set<T, S>(this T target, Expression<Func<T, S>> expression)
{
var propertyName = expression.GetPropertyName();
var fieldName = propertyName + "@";
var field = typeof (T).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field == null)
throw new Exception(
string.Format("Backing field {0} for property {1} could not be found.",
fieldName, propertyName));
return Tuple.Create(target, field);
}
public static T To<T, S>(this Tuple<T, FieldInfo> tuple, S value)
{
tuple.Item2.SetValue(tuple.Item1, value);
return tuple.Item1;
}
public static T With<T, S>(this T target, Expression<Func<T, S>> expression, S value)
{
return target.Set(expression).To(value);
}
}
// Usage in C#
var parameters =
ILMergeHelper.ILMergeDefaults
.Set(p => p.Closed).To(true)
.Set(p => p.CopyAttributes).To(false);
@forki
Copy link
Author

forki commented Mar 1, 2011

The idea is to provide access to F# records in C# test projects. I would not use this in production code.

@forki
Copy link
Author

forki commented Mar 1, 2011

Push this into FSharp.Testing. https://github.com/forki/FSharp.Testing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment