Geek and software developer who started writing in Basic (on Atari, Commodore and Amiga 500) in the 80's. I teach via this blog and videocasts. I have a lot of computers and even more monitors. Contact me at sebastian at brukalo dot com
Off the Ridge code
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:
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]
var properties =
BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
if (property.Name == name && property.CanRead)
return property.GetValue(this, null);
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.