1

I have couple of domain objects something like:

public class Person()
{
public int age { get; set; }
public string city{ get; set; }  
}

public class Company()
    {
    public string name{ get; set; }
    public string address{ get; set; }  
    }

I have another class which calls the MyMethod as mentioned below.

public class CallTest()
{
 Person p= new Person{age=10,city="dd"};
 Company c= new Company{name="mynae",address="myaddress"};
 MyMethod(p);
 MyMethod(c);
}

mi.Name gives me the property name. But how do I get the property value?

public class MyMethod(object obj)
{
    Type t = obj.GetType();
    PropertyInfo prop = t.GetProperty("Items");
    foreach (MemberInfo mi in t.GetMembers())
            {
                    if (mi.MemberType == MemberTypes.Property)
                    {
                       var x = mi.Name;
                    }
                }
}
1

2 Answers 2

2

You need to cast MemberInfo to PropertyInfo to get it's value :

.....
if (mi.MemberType == MemberTypes.Property)
{
    var x = mi.Name;
    var value = ((PropertyInfo) mi).GetValue(obj);
}
.....
Sign up to request clarification or add additional context in comments.

Comments

0

To get the value of property obj.Items you can use the following code

public class MyMethod(object obj)
{
    Type t = obj.GetType();
    PropertyInfo prop = t.GetProperty("Items");
    var x = prop.GetValue(obj, null);
}

2 Comments

It doesn't work, because we have to get value of the each property. When i tried your approach it throws null exception.
Ok i miss understood the question, i thought you were trying to get the value of "Items".

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.