1

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?

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

4 Comments

OK, but isn't this just regular reflection rather than expression parsing?
I'm not sure I follow the distinction you're making. I added example usage to the answer. Hopefully that will help clarify.
@bp123 Both LINQ Expressions and F# quotations work with .Net reflection types. There is no text parsing (is that what you meant?) in either case.
Gotcha - this is due to my ignorance, apologies. I thought that parsing an expression in C# for the purposes of a function like the one I posted was different than reflection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.