Off the Ridge Code Newsletter

Search

All posts in "reflection"

Calling object property via string.

Published June 10, 2014 in C# , reflection - 0Comments

CALLING OBJECT PROPERTY VIA STRING

How to call object’s property via its string name.


Recently, I needed a way to invoke object’s property via string, instead of its real name, yes I sacrificed the compile time checking :)

What do I mean by that?

Instead of writing code like this:

class SampleObject
{
   public Property1{get;set;}
}
SampleObject o = new SampleObject()
o.Property1 = "some value";

I needed a way to do this:

o."Property1" = "some value";

One simple (enough) way to accomplish this is by implementing an object indexer inside the class combined with reflection:

public object this[string name]
{
get
{
var properties =
        typeof(SampleObject).GetProperties(
              BindingFlags.Public | BindingFlags.Instance);
   foreach (var property in properties)
   {
      if (property.Name == name && property.CanRead)
      {
         return property.GetValue(this, null);
      }
   }
}
 set{......}
}


and Voilà

Now I can call the object via string like this:

to get value:
var myValue = o[“Property1”];

to set value:
o[“Property1”] = “SomeValue” // see my sample project for details.

You can download my sample project here.

Happy coding!