Last Updated: February 25, 2016
·
1.022K
· iondrimba

Simple Reflection via String input C#

public class YourClass
{
    private SomeCustomClass _person;
    public SomeCustomClass Person;
    {
        get{return _person;}
        set{_person = value;}
    }

    public YourClass()
    {
        _person = new SomeCustomClass();
    }

    /***** HERE IS WHERE THE MAGIC HAPPENS *****/
    public object GetPropertyValue(object SourceClass, string propName)
    {
        return SourceClass.GetType().GetProperty(propName).GetValue(SourceClass, null);
    }
}

//HOW TO USE:

YourClass model = new YourClass();
SomeCustomClass demo =  (SomeCustomClass)model.GetPropertyValue(model, "Person");  

This is usefull when you have to get properties based on some Enum you have on your application.

//ITERATING OVER ENUM: 

YourClass model = new YourClass();
foreach (YourEnum val in Enum.GetValues(typeof(YourEnum)))
{
    ISomeInterface status =  (ISomeInterface)model.GetPropertyValue(model, val);  
}