Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name of object within another object

I have a class called Prescriptions. It has properties that are other classes. So, for example, a property name of Fills would be from the PDInt class which has other properties about the value that I need.

If I want to set the value of the Fills property in the Prescription class it would be something like

Prescription p = new Prescription(); p.Fills.Value = 33;

So now I want to take the name of the Fills property and stuff it in a the tag property in a winform control.

this.txtFills.Tag = p.Fills.GetType().Name;

However when I do this, I get the base class of the property, not the property name. So instead of getting "Fills", I get "PDInt".

How do I get the instantiated name of the property?

Thank you.

like image 397
Mike Malter Avatar asked Feb 24 '23 15:02

Mike Malter


1 Answers

Below is an extension method that I use it when I wanna work like you:

public static class ModelHelper
{
    public static string Item<T>(this T obj, Expression<Func<T, object>> expression)
    {
        if (expression.Body is MemberExpression)
        {
            return ((MemberExpression)(expression.Body)).Member.Name;
        }
        if (expression.Body is UnaryExpression)
        {
            return ((MemberExpression)((UnaryExpression)(expression.Body)).Operand)
                    .Member.Name;
        }
        throw new InvalidOperationException();
    }
}

use it as :

var name = p.Item(x=>x.Fills);

For detail about how method works see Expression Tree in .Net

like image 92
Saeed Amiri Avatar answered Mar 04 '23 03:03

Saeed Amiri