Use Reflection in C# to dynamically retrieve properties

One good thing about JavaScript is the simplicity of working on object property. For example,  to traverse all properties of an object:

for(var propNamein myObject){
// Access the property value like this -
// myObject[propName] or myObject.propName
}

You may want to use hasOwnProperty () and isPropertyEnumerable to further filter the properties but it is simple enough.

Also to add or delete a property is just as simple as

Delete myObject.propName; // Delete property
myObject.propName = propValue;  //Add property

The best part is that you can retrieve a property just using a string variable to match its name.

var propName = "color";

var rabbit = {};
rabbit.color = "white";
console.log(rabbit[propName]); // it prints "white"

Of course, a well-developed language such as C# must also have a way to dynamically work on properties – Reflection.

Reflection can achieve many things but here we are only going to talk about property manipulation.

To get a list of properties of an object –

PropertyInfo[] propObjects = myObject.GetType().GetProperties();
// This returns an array of PropertyInfo objects,
// which is basically your property.

To traverse an object’s properties and work with them –

foreach(PropertyInfo prop in propObjects)
{
// access the property's name - prop.Name
// access the property's value - prop.GetValue(myObject)
// to set a property's value - prop.SetValue(myObject, propValue);
}

It is worth mentioning that when retrieving a certain property with name, ignoring case may be needed. To achieve that –

var value =
  myObject
   .GetType()
   .GetProperty(
    propName,
    BindingFlags.IgnoreCase|BindingFlags.Public|BindingFlags.Instance
    )
   .GetValue(myObject);

Note that all three binding flags are necessary, otherwise it won’t work.

Reference:

C# Reflection