1

How can I get this anonymous function to return "object.Property" as a string?

() => object.Property;

Thanks!

2
  • What type is object.Property to start with? Commented Jan 6, 2010 at 11:08
  • I'm trying to pass strongly typed property names to a function. Instead of coding "Article.Title" as a string, I'd prefer to pass ()=> Article.Title. Is this even clear? Commented Jan 6, 2010 at 11:12

2 Answers 2

3

Edit following clarification of requirements:

var foo = GetYourObjectFromSomewhere();
string bar = ExprToString(() => foo.Property);    // bar = "foo.Property"

// ...

public static string ExprToString<T>(Expression<Func<T>> e)
{
    // use a stack and a loop so that we can cope with nested properties
    // for example, "() => foo.First.Second.Third.Fourth.Property" etc

    Stack<string> stack = new Stack<string>();

    MemberExpression me = e.Body as MemberExpression;
    while (me != null)
    {
        stack.Push(me.Member.Name);

        me = me.Expression as MemberExpression;
    }

    return string.Join(".", stack.ToArray());
}

Original answer:

It's not entirely clear what you need, or what the type of object.Property is in the first place. Maybe one of the following would do the trick?

// either
() => (string)object.Property

// or
() => object.Property.ToString()

Sign up to request clarification or add additional context in comments.

Comments

2

Based on your additional explanation and requirements, you can solve this by asking for an Expression<Func<T, TProperty>> instaed of a Func<T, TProperty>.

You could implement this something like this:

public string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertyPicker)
{
     MemberExpression me = (MemberExpression)propertyPicker.Body;
     return me.Member.Name;
}

This would allow you to call it like this:

string name = GetPropertyName(x => x.Property);

since there exists an implicit conversion from Func<T, TResult> to Expression<Func<T, TResult>>.

A more complete explanation, as well as a reusable API can be found on Kzu's blog.

Comments

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.