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);
}
Written by Ion D. Filho
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#.net
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#