Alex Rivera | Logout

C# Using the Dynamic keyword to access properties via strings without reflection

Asked 2010-05-06T18:35:09.633
12

I would like to write something similar to the following:

//  I will pass in a number of "properties" specified as strings that I want modified
string[] properties = new [] { "AllowEdit", "AllowDelete" };

//  Casting the component I'm using to a dynamic object of some sort ?
dynamic d = myGridComponent;

//  Iterate over the strings and set the properties
foreach(var s in properties) 
{
  //d.s = true; // 
  //d[s] = true; // this format would be ideal
}

I was wondering if there was an easy way to do this without using Reflection [.GetProperty(...).GetValue(...,...)] using the new C# 4.0 keyword: dynamic.

It seems that there may be some way, ... I'm just not sure of the exact mechanism, and haven't been able to find the right resource to put all the pieces together.

Thoughts ?

[EDIT] It looks like there is a package called "Clay" that implements this type of functionality in some way. Clay on CodePlex
Scott Hanselman on the Subject

Edit
Report

2 Answers

3

No. dynamic in C# doesn't offer that. With your two examples:

d.s = true; // this looks for a property or field called "s"
d[s] = true; // this looks for an indexer that matches the string/bool signature

You can write the same code that dynamic offers, but it would be a lot harder than just using reflection. Either use reflection (as per your example), or if you need to optimise it you can optionally wrap it in a delegate, via either Expression or Delegate.CreateDelegate.

answered 2010-05-06T18:37:12.577
2

The opensource framework Impromptu-interface available via nuget encapsulates the code that dynamic would generate in a fully dynamic fashion. It's not as fast as using the dynamic keyword, but is faster than reflection.

foreach(var s in properties) 
{
  //d.s = true; 
  Impromptu.InvokeSet(d, s, true);
}
answered 2011-07-18T19:03:14.553

Your Answer