1

I need a method that returns a string representation based on a nested expression and i have some problems writing it. Let me explain this in code.

Let's say i have this object structure:

public class RandomClass
{
    public InnerRandomClass RandomProperty { get; set; }
}

public class InnerRandomClass
{
    public int SomeId { get; set; }
}

Then i have a method called Test. This method should be called like this an

var someString = Test(x => x.RandomProperty.SomeId);

And the expected return value in this case should be

Assert.AreEqual("RandomProperty.SomeId", someString);

I can write a method that returns "SomeId" but in my scenario i want the entire property structure, so i want "RandomProperty.SomeId".

I cant find anyone that wants to do something similar to this and i have inspected the Expression while debugging but cant find any information that helps.

I am aware that the solution might be pretty simple :D

Any suggestions on how the Test(Expression<Func<RandomClass, object>> expression) method should be implemented?

Thanks :)

Diemauerdk
  • 5,238
  • 9
  • 40
  • 56
  • 1
    The expression has everything you need to construct this, and examining it at debug time will give you all the info you need. Not sure why you're having a problem. Maybe [edit] and include the structure of the expression (expanded down to SomeId) and why you're having problems following the expression tree. –  Jan 10 '18 at 14:50
  • 1
    It's not so pretty simple, but also nit that hard :) Doesn't some of the answers of [Retrieving Property name from lambda expression](https://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression) work for you? – Ivan Stoev Jan 10 '18 at 14:56
  • 1
    Thanks for the feedbakc. I'll take a look at the links and combine this with Darjan's anwer to find a fitting implementation :) – Diemauerdk Jan 11 '18 at 07:33

1 Answers1

1

Really simple and pragmatic solution (avoids tree traversal), please keep in mind there are certain corner cases or limitations like using collections or methods.

public string Test(Expression<Func<RandomClass, object>> expression)
{
    if (expression.Body is UnaryExpression eBody)
    {
        string expr = eBody.Operand.ToString().ToString();
        var dotIndex = expr.IndexOf(".");
        return expr.Substring(dotIndex + 1);
    }
    return string.Empty;
}
Darjan Bogdan
  • 3,780
  • 1
  • 22
  • 31