Created
March 1, 2011 07:57
-
-
Save forki/848791 to your computer and use it in GitHub Desktop.
FSharpRecordExtensions to allow (mutable) With-Syntax in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage in C# | |
var parameters = | |
ILMergeHelper.ILMergeDefaults | |
.Set(p => p.Closed).To(true) | |
.Set(p => p.CopyAttributes).To(false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea is to provide access to F# records in C# test projects. I would not use this in production code.