C# reflection get property value code example

Example 1: c# get property using string

public static object GetPropValue(object src, string propName)
 {
     return src.GetType().GetProperty(propName).GetValue(src, null);
 }

Example 2: get property value from object c#

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    object propValue = prop.GetValue(myObject, null);

    // Do something with propValue
}

Example 3: find class property with string C#

//Add this to class
public class MyClass 
{
    public object this[string property]
    {
        get
        {
            return typeof(security).GetProperty(property).GetValue(this, null);
        }
        set
        {
            typeof(security).GetProperty(property).SetValue(this, value, null);
        }
    }
}