Diemauerdk
Diemauerdk

Reputation: 5938

Nested properties reflection C#

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 :)

Upvotes: 1

Views: 78

Answers (1)

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

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;
}

Upvotes: 1

Related Questions