Reputation: 195
As a newbie to F#, I routinely try to convert bits of C# over as a learning exercise. In this case, I am trying to convert the following C# expression parsing code. It's simple, the idea is to pass a lambda into this function to get the string representation of a property name, rather than using standard reflection techniques. I have omitted the other GetMemberName function as I think I can figure it out once I get some guidance on what approach to take.
public static string GetMemberName<T>(Expression<Func<T, object>> expression)
{
if (expression == null)
{
throw new ArgumentException("The expression cannot be null.");
}
return GetMemberName(expression.Body);
}
I know that F# has quotations. I also know I could use Linq Expressions in F#. I would like to try it the F# way first using quotations, but I am stumbling. Could someone give me a kickstart?
Upvotes: 1
Views: 182
Reputation: 47904
I'm not sure if an exact translation of this is possible using quotations because quotations have a different shape than C# expressions. However, here's something along the same lines:
open Microsoft.FSharp.Quotations.Patterns
let GetMemberName = function
| Call (_,methodInfo,_) -> methodInfo.Name
| PropertyGet (_,propertyInfo,_) -> propertyInfo.Name
| _ -> failwith "Not a member expression"
GetMemberName <@ [].IsEmpty @>
// val it : string = "IsEmpty"
Upvotes: 3